uint8_t iostream behavior

前端 未结 3 2184
误落风尘
误落风尘 2020-12-10 12:48

Abstract: I was expecting the code: cout << uint8_t(0); to print \"0\", but it doesn\'t print anything.

Long version: When I try to stream uint8_t objects

相关标签:
3条回答
  • 2020-12-10 13:11

    As others have pointed out, uint8_t is streamed as an unsigned char. I've sometimes made use of bit fields from integer types that are streamed as, well, integers, to avoid having to cast or overload operator<<, but only when it doesn't waste space, like in the Pos struct 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 讨论(0)
  • 2020-12-10 13:22

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

    The conversion to integer inhibits this.

    0 讨论(0)
  • 2020-12-10 13:24

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

    Absolutely. It's required to be a typedef for a builtin 8-bit unsigned integral type, if such a type exists. Since there are only two possible 8-bit unsigned integral types, char for a compiler that treats it as unsigned and unsigned char, it must be one of those. Except on systems where char is larger than 8 bits, in which case it won't exist.

    0 讨论(0)
提交回复
热议问题