From: Adam Preble Date: 2007-10-26T01:09:13+09:00 Subject: Re: read write integer in binary into a file I wrote a function to do this which seems slightly faster, but could perhaps stand some optimization: def pack_int32(n) str = ' ' str[3] = n >> 24 str[2] = n >> 16 str[1] = n >> 8 str[0] = n str end Here are the benchmark results vs the other methods mentioned: user system total real [].pack(i): 6.234000 0.235000 6.469000 ( 6.500000) pack_int32: 5.719000 0.015000 5.734000 ( 5.734000) Marshal.dump: 6.594000 0.219000 6.813000 ( 6.813000) I included Marshal.dump for completeness, but agree that it doesn't appear to be meant for this sort of thing. Here's the source to run the benchmark: require 'benchmark' number = 2_000_000 n = 1_000_000 Benchmark.bm(12) do |x| x.report('[].pack(i):') { n.times do; [number].pack('i'); end } x.report('pack_int32:') { n.times do; pack_int32(number); end } x.report('Marshal.dump:') { n.times do; Marshal.dump(number); end } end Adam On Oct 25, 10:36 am, Vianney Lecroart wrote: > Hello, > > I have some big files with lot of "unsigned int" (4 bytes) numbers and I > want to read and write on these files. > > Currently, I found this to write: > > myfile << [mynum].pack("i") > > and to read: > > mynum = myfile.read(4).unpack("i").first > > I wonder if there's not something faster/simpler to do that without the > need to convert the number into an array into a string to finally > serialize it. > > Thank you.