Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ruby to convert unsigned integers stored as signed back to the original value

A C-program is placing what it considers to be 64-bit unsigned integers into a column in a Postgres database that is typed as int8. To Postgres, int8 is always 'signed int8' (no such thing to it as 'unsigned int8'). So the Ruby program I have shows numbers retrieved from Postgres in the upper half of that space as negative.

What is the correct way, in Ruby, to take that -ve integer and convert it to the 64-bit unsigned integer that the C-programmer intended?

like image 553
Mike Berrow Avatar asked Nov 19 '25 22:11

Mike Berrow


1 Answers

I'm not sure of Ruby specifics, but essentially you need to add 2^64 if the number is negative. That's assuming the number is stored as 2's complement, which it almost certainly is.

FYI, the 2's complement system, essentially it treats a (say) 32-bit number as a number mod 2^32. This means -1 is the same thing as 2^32 - 1 or 0xFFFFFFFF. This turns out to be really simple to use at a hardware level.

like image 75
Artelius Avatar answered Nov 21 '25 19:11

Artelius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!