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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With