Robert Klemme
6/1/2006 8:29:00 AM
Dave Burt wrote:
> BT wrote:
>> Hi,
>>
>> I am new to Ruby and have been unable to figure out how to accomplish
>> the following task:
>>
>> I would like to read a certain number of bytes from a binary file, then
>> convert those bytes into a large integer.
>>
>> Say the 1st 4 bytes of the binary file were 0xAF 0xBB 0x1C 0xFF. I'd
>> like to read those 4 bytes from the file and convert them into the
>> [base 10] integer, 2,948,275,455.
>
> n = array_of_bytes.inject(0){|n, b| (n << 8) + b }
>
> With a file, you might try something like this:
>
> n = 0
> File.open "filename" do |f|
> 4.times { n = n << 8 + f.getc }
> end
For efficiency reasons both approaches can be combined:
File.open "filename" do |f|
n = 0
4.times { n = (n << 32) | (f.read(4).unpack("N")[0]) }
n
end
This one is even nicer:
File.open("your-file", "rb") do |f|
f.read(6 * 4).unpack("N6").inject(0) {|sum, x| sum << 32 | x}
end
Kind regards
robert