【发布时间】:2018-09-07 13:17:06
【问题描述】:
我需要读取包含一列数字(时间标签)的二进制数据,并使用 8 个字节来记录每个数字。我知道它们是以 little endian 顺序记录的。如果读取正确,它们应该被解码为(示例)
...
2147426467
2147426635
2147512936
...
我知道上述数字在 2^31 -1 阈值上。 我尝试读取数据并通过以下方式反转字节序: (length 是字节总数,buffer 是指向包含字节的数组的指针)
unsigned long int tag;
//uint64_t tag;
for (int j=0; j<length; j=j+8) //read the whole file in 8-byte blocks
{ tag = 0;
for (int i=0; i<=7; i++) //read each block ,byte by byte
{tag ^= ((unsigned char)buffer[j+i])<<8*i ;} //shift each byte to invert endiandness and add them with ^=
}
}
运行时,代码给出:
...
2147426467
2147426635
18446744071562097256
similar big numbers
...
最后一个数字不是(2^64 - 1 - 正确值)。 使用 uint64_t 标签 的结果相同。 代码成功声明标签为
unsigned int tag;
但对于大于 2^32 -1 的标签会失败。至少这是有道理的。
我想我需要在 buffer[i+j] 上进行某种类型的转换,但我不知道该怎么做。
(static_cast<uint64_t>(buffer[j+i]))
也不行。
我读了a similar question,但仍然需要一些帮助。
【问题讨论】:
-
@jxh 如何将其提升为 unsigned long 而不是 signed int ?
-
buffer的类型是什么? -
@user2079303 它被声明为 char
char *buffer = new char[length];
标签: c++ casting binaryfiles endianness