[英]Convert array of bytes to uint64_t?
I have a large array of bytes called memory and I'm trying to convert 8 of those bytes to a uint64_t. 我有一个大的字节数组称为内存,我正在尝试将这些字节中的8个转换为uint64_t。 I'm trying to print the number in big-endian.
我正在尝试用big-endian打印数字。
I have this so far: 到目前为止我有这个:
uint64_t value = (uint64_t)(memory[256]) | //location contains byte 88
(uint64_t)(memory[257]) << 8 | //77
(uint64_t)(memory[258]) << 16 | //66
(uint64_t)(memory[259]) << 24 | //55
(uint64_t)(memory[260]) << 32 | //44
(uint64_t)(memory[261]) << 40 | //33
(uint64_t)(memory[262]) << 48 | //22
(uint64_t)(memory[263]) << 56; //11
I print like so: 我是这样打印的:
printf("0x%x", value);
The output is 0x55667788
, but I want the output to be 0x1122334455667788
. 输出为
0x55667788
,但我希望输出为0x1122334455667788
。
Any suggestions of how I can fix the above code to print 0x1122334455667788
? 有关如何修复上述代码以打印
0x1122334455667788
任何建议?
Solution: The print statement needed to be: 解决方案:print语句必须是:
printf("0x%lx", value);
The format specifier %lx
works because the unsigned long
type happens to have at least 64 bits on your system. 格式说明符
%lx
有效,因为unsigned long
类型恰好在系统上至少有64位。 The C Standard does not guarantee that and indeed it has only 32 bits on 64-bit Microsoft Windows. C标准并不能保证64位Microsoft Windows上只有32位。
unsigned long long
is guaranteed to have at least 64 bits, so you could use this: unsigned long long
保证至少有64位,所以你可以使用这个:
printf("0x%llx\n", (unsigned long long)value);
If your compiler and C library support C99 or a later standard, you can use the macros defined in <inttypes.h>
: 如果您的编译器和C库支持C99或更高版本的标准,则可以使用
<inttypes.h>
定义的宏:
printf("0x%" PRIx64 "\n", value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.