【发布时间】:2018-08-07 15:28:56
【问题描述】:
我是C++ 编程的新手。我正在尝试实现一个代码,通过它我可以从6 或更多individual bytes 中生成一个整数值。
我已经为 4 bytes 实现了相同的功能,它正在工作
我的 4 字节代码:
char *command = "\x42\xa0\x82\xa1\x21\x22";
__int64 value;
value = (__int64)(((unsigned char)command[2] << 24) + ((unsigned char)command[3] << 16) + ((unsigned char)command[4] << 8) + (unsigned char)command[5]);
printf("%x %x %x %x %x",command[2], command[3], command[4], command[5], value);
使用此代码,value 的值是82a12122,但是当我尝试执行 6 字节时,结果是错误的。
6 字节代码:
char *command = "\x42\xa0\x82\xa1\x21\x22";
__int64 value;
value = (__int64)(((unsigned char)command[0] << 40) + ((unsigned char)command[1] << 32) + ((unsigned char)command[2] << 24) + ((unsigned char)command[3] << 16) + ((unsigned char)command[4] << 8) + (unsigned char)command[5]);
printf("%x %x %x %x %x %x %x", command[0], command[1], command[2], command[3], command[4], command[5], value);
value 的输出值是82a163c2 这是错误的,我需要42a082a12122。
那么谁能告诉我如何获得预期的输出以及6 Byte 代码有什么问题。
提前致谢。
【问题讨论】:
-
(unsigned char)command[0] << 40,你的无符号字符,将被提升为int,在你的情况下,它的字节数比int64_t少。 -
不要使用
%x,对于字符使用%hhx,对于int64%llxin printf -
您必须在转换前将其转换为
_int64。 -
@IlyaBursov:从技术上讲,如果你想小心点,you'd use the
inttypes.hmacros likePRIx64而不是猜测像ll这样的相对宽度前缀和固定位宽类型之间的对应关系。或者因为它是 C++,你只需使用iostream和std::cout并完全避免这个问题。 -
这实际上是 C++ 吗?对我来说看起来像是低级 C。
标签: c++ integer byte-shifting