Why is std::cout not printing the correct value for my int8_t number?

前端 未结 4 1804
北海茫月
北海茫月 2020-11-28 14:47

I have something like:

int8_t value;
value = -27;

std::cout << value << std::endl;

When I run my program I get a wrong random

4条回答
  •  我在风中等你
    2020-11-28 15:12

    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

    std::cout << (int) 'a' << std::endl;
    

    This will work, as long as you don't require special formatting, e.g.

    std::cout << std::hex << (int) 'a' << std::endl;
    

    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

提交回复
热议问题