为什么 std::cout 没有打印我的 int8_t 数字的正确值?
我有这样的情况:
int8_t value;
value = -27;
std::cout << value << std::endl;
当我运行程序时,我得到一个错误的
随机值输出到屏幕,但是当我在 gdb 中运行程序并使用 p value
code> 它打印出 -27,这是正确的值。有人有什么想法吗?
I have something like:
int8_t value;
value = -27;
std::cout << value << std::endl;
When I run my program I get a wrong random value of <E5>
outputted to the screen, but when I run the program in gdb and use p value
it prints out -27, which is the correct value. Does anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为
int8_t
与signed char
相同,并且char
不会被流视为数字。转换为例如int16_t
,您将得到正确的结果。
Because
int8_t
is the same assigned char
, andchar
is not treated as a number by the stream. Cast into e.g.int16_t
and you'll get the correct result.
这是因为 int8_t 与 signed char 同义。
因此该值将显示为字符值。
要强制 int 显示,您可以使用
这将起作用,只要您不需要特殊格式,例如,
在这种情况下,您将从加宽的大小中获得伪影,特别是如果 char 值为负数(您将得到 FFFFFFFF 或FFFF1 表示
(int)(int8_t)-1
而不是 FF)编辑 另请参阅这篇非常易读的文章,其中提供了更多详细信息并提供更多策略要“处理”此问题:http://blog.mezeske.com/?p=170
<子 >
1 取决于架构和编译器
This is because int8_t is synonymous to signed char.
So the value will be shown as a char value.
To force int display you could use
This will work, as long as you don't require special formatting, e.g.
In that case you'll get artifacts from the widened size, especially if the char value is negative (you'd get FFFFFFFF or FFFF1 for
(int)(int8_t)-1
instead of FF)Edit see also this very readable writeup that goes into more detail and offers more strategies to 'deal' with this: http://blog.mezeske.com/?p=170
1 depending on architecture and compiler
最有可能的是
int8_t
是因此,当您使用流输出“值”时,会打印基础类型(字符)。
打印“整数”的一种解决方案是在流式传输 int8_t 之前输入强制转换值:
Most probably
int8_t
isTherefore when you use stream out "value" the underlying type (a char) is printed.
One solution to get a "integer number" printed is to type cast value before streaming the int8_t:
看起来它正在将值打印为字符 - 如果您使用“char value;”相反,它打印相同的内容。 int8_t 来自 C 标准库,因此可能是 cout 没有为它做好准备(或者它只是 typedefd 到 char)。
It looks like it is printing out the value as a character - If you use 'char value;' instead, it prints the same thing. int8_t is from the C standard library, so it may be that cout is not prepared for it(or it is just typedefd to char).