Uint8_t iostream behavior

Summary: I was expecting code: cout <uint8_t (0); printable "0", but does not print anything.

Long version: when I try to pass uint8_t objects to cout, I get weird characters with gcc. Is this expected behavior? Maybe uint8_t is an alias for some type of char? See Compiler / System Notes in the sample code.

// compile and run with: // g++ test-uint8.cpp -std=c++11 && ./a.out // -std=c++0x (for older gcc versions) /** * prints out the following with compiler: * gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2) * on the system: * Linux 3.7.9-101.fc17.x86_64 * Note that the first print statement uses an unset uint8_t * and therefore the behaviour is undefined. (Included here for * completeness) > g++ test-uint8.cpp -std=c++11 && ./a.out >>> <<< >>>194<<< >>><<< >>>0<<< >>><<< >>>0<<< >>><<< >>>0<<< >>><<< >>>1<<< >>><<< >>>2<<< * **/ #include <cstdint> #include <iostream> void print(const uint8_t& n) { std::cout << ">>>" << n << "<<< " << ">>>" << (unsigned int)(n) << "<<<\n"; } int main() { uint8_t a; uint8_t b(0); uint8_t c = 0; uint8_t d{0}; uint8_t e = 1; uint8_t f = 2; for (auto i : {a,b,c,d,e,f}) { print(i); } } 
+9
c ++ iostream c ++ 11
Mar 08 '13 at 14:47
source share
3 answers

uint8_t is an alias for unsigned char , and iostreams have special overloads for characters that print characters rather than format numbers.

Converting to an integer forbids this.

+9
Mar 08 '13 at 14:49
source share

Could it be that uint8_t is an alias for some type of char?

That's right. It must be a typedef for the built-in 8-bit unsigned integral type, if one exists. Since there are only two possible 8-bit unsigned integral types, char for the compiler, which treats it as unsigned and unsigned char , should be one of them. Except for systems where char greater than 8 bits, in which case it will not exist.

+5
Mar 08 '13 at 14:54
source share

As others have noted, uint8_t is passed as an unsigned char . I sometimes used bit fields from integer types that are passed as integers or integers to avoid the need to throw or overload operator<< , but only when it does not lose space, as in the Pos structure below:

 #include <iostream> struct WasteAbyte { unsigned short has_byte_range:8; }; struct Pos { unsigned short x:8; unsigned short y:8; }; int main() { WasteAbyte W = {255}; ++W.has_byte_range; std::cout << W.has_byte_range << std::endl; std::cout << sizeof(WasteAbyte) << std::endl; std::cout << sizeof(Pos) << std::endl; return 0; } 

Output:

 0 2 2 
0
Nov 23 '17 at 19:33
source share



All Articles