Reading a binary 16-bit signed (big-endian) integer in Ruby

I tried reading from a file where numbers are stored as 16-bit signed integers in big-endian format.

I used the decompression to read in the number, but for a 16-bit signed integer in big-endian format there is no parameter, only for an unsigned integer. Here is what I still have:

number = f.read(2).unpack('s')[0]

Is there a way to interpret the number above as a signed integer or another way to achieve what I want?

+3
source share
4 answers

Found a solution that works by reading two 8-bit unsigned integers and converting them to a 16-bit integer

bytes = f.read(2).unpack('CC')  
elevation = bytes[0] << 8 | bytes[1]
+1
source

, String#unpack, , , 16- :

>> value = 65534
>> (value & ~(1 << 15)) - (value & (1 << 15))
=> -2

:

class Integer
  def to_signed(bits)
    mask = (1 << (bits - 1))
    (self & ~mask) - (self & mask)
  end
end

p 1001.to_signed(16) # => 1001
p 65534.to_signed(16) # => -2
+6

Use BinData , and there is no need to beat.

BinData::Int16be.read(io)
+3
source

Apparently with Ruby 1.9.3 you can really suffix susing endiannes: io.read(2).unpack('s>')

0
source

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


All Articles