22

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?

Grammin
  • 11,808
  • 22
  • 80
  • 138

4 Answers4

34

Because int8_t is the same as signed char, and char is not treated as a number by the stream. Cast into e.g. int16_t

std::cout << static_cast<int16_t>(value) << std::endl;

and you'll get the correct result.

Martin York
  • 257,169
  • 86
  • 333
  • 562
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 2
    since the type of int16_t may not be an integer (as the stream understands it) maybe you should case to `int`. – Martin York Sep 28 '11 at 19:46
4

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

sehe
  • 374,641
  • 47
  • 450
  • 633
3

Most probably int8_t is

typedef char int8_t

Therefore 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:

std::cout << static_cast<int>(value) << std::endl;
Carsten Greiner
  • 2,928
  • 2
  • 16
  • 20
1

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).

Nathaniel Flath
  • 15,477
  • 19
  • 69
  • 94