Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

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

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?

like image 981
sliver Avatar asked Dec 17 '22 17:12

sliver


1 Answers

I don't know if it's possible to use String#unpack for that, but to convert a 16bit-unsigned to signed, you can use the classical method:

>> value = 65534
>> (value & ~(1 << 15)) - (value & (1 << 15))
=> -2
like image 95
tokland Avatar answered Mar 25 '23 01:03

tokland