从二进制文件读取double(字节顺序?) [英] Reading double from binary file (byte order?)
问题描述
我有一个二进制文件,我想从中读取一个double。
I have a binary file, and I want to read a double from it.
在十六进制表示中,我在文件中有这8个字节(然后是一些之后更多):
In hex representation, I have these 8 bytes in a file (and then some more after that):
40 28 25 c8 9b 77 27 c9 40 28 98 8a 8b 80 2b d5 40 ...
40 28 25 c8 9b 77 27 c9 40 28 98 8a 8b 80 2b d5 40 ...
这应该对应于大约10的双倍值(基于该条目的含义)。
This should correspond to a double value of around 10 (based on what that entry means).
我使用过
#include<stdio.h>
#include<assert.h>
int main(int argc, char ** argv) {
FILE * f = fopen(argv[1], "rb");
assert(f != NULL);
double a;
fread(&a, sizeof(a), 1, f);
printf("value: %f\n", a);
}
然而,打印
值:-261668255698743527401808385063734961309220864.000000
However, that prints value: -261668255698743527401808385063734961309220864.000000
很明显,字节不能正确转换为double。到底是怎么回事?
使用ftell,我可以确认正在读取8个字节。
So clearly, the bytes are not converted into a double correctly. What is going on? Using ftell, I could confirm that 8 bytes are being read.
推荐答案
就像整数类型一样,浮点类型受平台字节序限制。当我在小端机器上运行这个程序时:
Just like integer types, floating point types are subject to platform endianness. When I run this program on a little-endian machine:
#include <stdio.h>
#include <stdint.h>
uint64_t byteswap64(uint64_t input)
{
uint64_t output = (uint64_t) input;
output = (output & 0x00000000FFFFFFFF) << 32 | (output & 0xFFFFFFFF00000000) >> 32;
output = (output & 0x0000FFFF0000FFFF) << 16 | (output & 0xFFFF0000FFFF0000) >> 16;
output = (output & 0x00FF00FF00FF00FF) << 8 | (output & 0xFF00FF00FF00FF00) >> 8;
return output;
}
int main()
{
uint64_t bytes = 0x402825c89b7727c9;
double a = *(double*)&bytes;
printf("%f\n", a);
bytes = byteswap64(bytes);
a = *(double*)&bytes;
printf("%f\n", a);
return 0;
}
然后输出
12.073796
-261668255698743530000000000000000000000000000.000000
这表明您的数据存储在文件中小端格式,但您的平台是大端。因此,您需要在读取值后执行字节交换。上面的代码显示了如何做到这一点。
This shows that your data is stored in the file in little endian format, but your platform is big endian. So, you need to perform a byte swap after reading the value. The code above shows how to do that.
这篇关于从二进制文件读取double(字节顺序?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!