user6167852
user6167852

Reputation: 35

How to convert in to signed int (4byte) using Ruby

I need to convert the follow 4 byte integer to signed integer, like:

input 65535 value -1 input 65534 value -2 input 65533 value -3 and so on...

I tried the follow:

 puts (65533).to_s(16) #=> fffd
 puts (65533).to_s(16).unpack('s') #=> doesn't work properly... return 26214

Can someone help me with code above? Best Regards

Upvotes: 2

Views: 440

Answers (1)

Stefan
Stefan

Reputation: 114178

You could pack it as as an unsigned integer and then unpack it as a signed integer:

[65535, 65534, 65533].pack('S*').unpack('s*')
#=> [-1, -2, -3]

S / s denote 16-bit integers, you can also use L / l for 32-bit or Q / q for 64-bit.

Upvotes: 3

Related Questions