为什么这个“int”的值是错误的?
不知道该怎么说,但我将从代码片段和输出开始:
uint32_t expires;
cout << "Expiration bytes: " << setfill('0') << hex
<< setw(2) << (unsigned short)rec[keyLen+4]
<< setw(2) << (unsigned short)rec[keyLen+5]
<< setw(2) << (unsigned short)rec[keyLen+6]
<< setw(2) << (unsigned short)rec[keyLen+7] << endl;
expires = ntohl(*(uint32_t*)&rec[keyLen+4]);
cout << "Expiration: " << (long)expires << endl;
cout << "Hex: " << hex << expires << endl;
输出:
Expiration bytes: 00000258
Expiration: 258
Hex: 258
我可以从程序的其他部分确认检查和输出字节的十六进制表示按预期工作,并且这些确实是字节流中的字节(从另一个应用程序发送)。
现在,如果 expiration
只是持有一些废话,我将能够更好地理解,因为这意味着存在一些严重的错误(可能涉及指针)。但这...这显然只是将十六进制值当作十进制值来输出,这显然是错误的。
更令人困惑的是,这在程序中的另一点起作用:
fullSize = ntohs(*(uint16_t*)&buff[0]);
当字节值为 0x0114 时,fullSize
将包含值 276。
所以问题是,这里到底发生了什么? int 怎么可能错误?
Not sure how else to put that, but I'll start off with a code snippet and output:
uint32_t expires;
cout << "Expiration bytes: " << setfill('0') << hex
<< setw(2) << (unsigned short)rec[keyLen+4]
<< setw(2) << (unsigned short)rec[keyLen+5]
<< setw(2) << (unsigned short)rec[keyLen+6]
<< setw(2) << (unsigned short)rec[keyLen+7] << endl;
expires = ntohl(*(uint32_t*)&rec[keyLen+4]);
cout << "Expiration: " << (long)expires << endl;
cout << "Hex: " << hex << expires << endl;
Outputs:
Expiration bytes: 00000258
Expiration: 258
Hex: 258
I can confirm from other parts of the program that examining and outputting the hex representation of bytes works as expected, and that those are indeed the bytes in the byte stream (sent from another application).
Now, I would be able to understand a bit better if expiration
just held some nonsense, because that would mean there's some egregious error (probably involving pointers). But this... this is clearly just spitting out the hex value as if it were a decimal, and that's plain wrong.
To make matters more confusing, this works at another point in the program:
fullSize = ntohs(*(uint16_t*)&buff[0]);
With a byte value of 0x0114, fullSize
will contain the value 276.
So the question is, what the heck is going on here? How is it possible for an int to be wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
hex
是粘性的,因此除非您重置它,否则cout
将继续以十六进制输出内容。您可以通过向流发送
std::dec
来重置它。或者,您可以构建一个更高级的机制来存储原始状态并在事后恢复它。hex
is sticky, so unless you reset it,cout
will continue to output things in hex.You can reset it by issuing sending
std::dec
to the stream. Alternatively you could build a more advanced mechanism that would store the original state and restore it afterwords.<代码>cout << “过期时间:”<<十二月 << (长)过期 << endl; 将输出十进制,否则最后的设置(
hex
或dec
)仍然有效。cout << "Expiration: " << dec << (long)expires << endl;
will output decimal, otherwise the last setting (hex
ordec
) will still be in effect.由于您从未将
cout
切换回十进制输出,因此所有输出都是十六进制,甚至cout <<的输出也是如此。 “过期时间:”<< (长)过期 <<结束;
。Since you never switch
cout
back to decimal output, all of your outputs are in hex, even the output ofcout << "Expiration: " << (long)expires << endl;
.