Ruby - read bytes from a file, convert to integer

I am trying to read unsigned integers from a file (stored as serial bytes) and convert them to integers. I tried this:

file = File.new(filename,"r")
num = file.read(2).unpack("S") #read an unsigned short
puts num #value  will be less than expected

What am I doing wrong here?

+3
source share
6 answers

Ok, I got it for work:

num = file.read(8).unpack("N")

Thank you for your help.

+1
source

You do not read enough bytes. As you say in the commentary to the tadman, you get 202instead3405691582

Note that the first 2 bytes 0xCAFEBABEare equal 0xCA=202

If you really want all 8 bytes to be in the same number, you need to read more than unsigned short

to try

num = file.read(8).unpack("L_")

, long 8 , .

+6

, The Pickaxe? (Ruby 1.9, . 44)

File.open("testfile") 
do |file|
    file.each_byte {|ch| print "#{ch.chr}:#{ch} " }
end

each_byte .

+4

, Ruby, DSL- , , , , - .

, . ( , ):

+2

, , Windows. , .

open(filename, "rb") do |file|
  num = file.read(2).unpack("S")
  puts num
end

"endian" . , PowerPC, Mac, IBM Power, PS3 Sun Sparc.

Can you post an example of how this is β€œless”? Usually there is an obvious template for data.

For example, if you want 0x1234, but you get 0x3412, this will be an end problem.

+1
source

In what format are the numbers stored in the file? Is it in the hex? Your code looks correct to me.

0
source

Source: https://habr.com/ru/post/1715932/


All Articles