Can uint8_t be a non-character type?

后端 未结 4 1754
后悔当初
后悔当初 2020-12-15 22:41

In this answer and the attached comments, Pavel Minaev makes the following argument that, in C, the only types to which uint8_t can be typedef\'d are char

相关标签:
4条回答
  • 2020-12-15 23:24

    If uint8_t exists, the no-padding requirement implies that CHAR_BIT is 8. However, there's no fundamental reason I can find why uint8_t could not be defined with an extended integer type. Moreover there is no guarantee that the representations are the same; for example, the bits could be interpreted in the opposite order.

    While this seems silly and gratuitously unusual for uint8_t, it could make a lot of sense for int8_t. If a machine natively uses ones complement or sign/magnitude, then signed char is not suitable for int8_t. However, it could use an extended signed integer type that emulates twos complement to provide int8_t.

    0 讨论(0)
  • 2020-12-15 23:26

    int8_t and uint8_t differ only by REPRESENTATION and NOT the content(bits). int8_t uses lower 7 bits for data and the 8th bit is to represent "sign"(positive or negative). Hence the range of int8_t is from -128 to +127 (0 is considered a positive value).

    uint8_t is also 8 bits wide, BUT the data contained in it is ALWAYS positive. Hence the range of uint8_t is from 0 to 255.

    Considering this fact, char is 8 bits wide. unsigned char would also be 8 bits wide but without the "sign". Similarly short and unsigned short are both 16 bits wide.

    IF however, "unsigned int" be 8 bits wide, then .. since C isn't too type-nazi, it IS allowed. And why would a compiler writer allow such a thing? READABILITY!

    0 讨论(0)
  • 2020-12-15 23:28

    In 6.3.1.1 (1) (of the N1570 draft of the C11 standard), we can read

    The rank of any standard integer type shall be greater than the rank of any extended integer type with the same width.

    So the standard explicitly allows the presence of extended integer types of the same width as a standard integer type.

    There is nothing in the standard prohibiting a

    typedef implementation_defined_extended_8_bit-unsigned_integer_type uint8_t;
    

    if that extended integer type matches the specifications for uint8_t (no padding bits, width of 8 bits), as far as I can see.

    So yes, if the implementation provides such an extended integer type, uint8_t may be typedef'ed to that.

    0 讨论(0)
  • 2020-12-15 23:30

    uint8_t may exist and be a distinct type from unsigned char.

    One significant implication of this is in overload resolution; it is platform-dependent whether:

    uint8_t by = 0;
    std::cout << by;
    

    uses

    1. operator<<(ostream, char)
    2. operator<<(ostream, unsigned char) or
    3. operator<<(ostream, int)
    0 讨论(0)
提交回复
热议问题