如何读取,使用R二进制文件64位二进制补码整数? [英] How to read a 64-bit two's-complement integer from a binary file using R?
问题描述
据我了解,重新present R中一个64位整数,我需要使用双。这很好,但我需要从它被存储为大端64位二进制补码(长在Java)的二进制文件中读取这样的整数。
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).
我当然可以读出两个有符号整数4字节的块,像这样
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")
但我怎么结合他们在R以获得我所需要的双?
But how do I combine them in R to get the double I require?
推荐答案
这绝对是更好地阅读它作为比为双两个整数。 2的补64位的幅度小的负数再presentation,如-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.
先取2的补问题了。我会认为 A
是较为显著的一半。如果它是负的,注意这一事实,并采取2的整数的补充。翻转所有位,然后添加一个来自矣 B
添加到 A
添加。
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.
接下来,转换 A
翻一番,由2 ^ 32乘,并添加 B
。
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.
这篇关于如何读取,使用R二进制文件64位二进制补码整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!