How to read a 64-bit two's-complement integer

2019-09-13 22:01发布

问题:

I gather that to represent a 64-bit integer in R I need to use a double. That's fine but I need to read such an integer from a binary file where it is stored as Big Endian 64-bit two's-complement (a java long).

I can of course read the two signed integers in 4 byte chunks like so

a = readBin(file, integer(), size=4, endian="big")
b = readBin(file, integer(), size=4, endian="big")

But how do I combine them in R to get the double I require?

回答1:

It is definitely better to read it in as two integers than as a double. The 2's complement 64 bit representation of small magnitude negative numbers, such as -1, are NaN's in double, and doing arithmetic on them will probably not work out the way you need.

First take the 2's complement issue out. I am going to assume that a is the more significant half. If it is negative, note the fact and take the 2's complement of the integer. Flip all the bits, then add one with carry from the b add to the a add.

Next, convert a to double, multiply by 2^32, and add b.

If the original value was negative, negate the result.

Note that you may not get the exact answer if the original number was too big.