简体   繁体   English

如何使用R从二进制文件中读取64位二进制补码整数?

[英]How to read a 64-bit two's-complement integer from a binary file using R?

I gather that to represent a 64-bit integer in RI need to use a double. 我收集到,要在RI中表示一个64位整数,需要使用一个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). 很好,但是我需要从二进制文件中读取这样的整数,该整数将以Big Endian 64位二进制补码(java长)存储。

I can of course read the two signed integers in 4 byte chunks like so 我当然可以像这样读取4字节块中的两个有符号整数

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? 但是,如何将它们结合到R中以获得所需的两倍?

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. 小数值负数(例如-1)的2补码64位表示形式是NaN的两倍,对它们进行算术运算可能无法满足您的需要。

First take the 2's complement issue out. 首先取出2的补码问题。 I am going to assume that a is the more significant half. 我将假设a是更重要的一半。 If it is negative, note the fact and take the 2's complement of the integer. 如果它是负数,请注意事实并取整数的2的补码。 Flip all the bits, then add one with carry from the b add to the a add. 翻转所有位,然后将带有b进位加到a

Next, convert a to double, multiply by 2^32, and add b . 接下来,将a转换为双精度,乘以2 ^ 32,然后加上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. 请注意,如果原始数字太大,您可能无法获得确切答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM