What is an unsigned char?

后端 未结 17 1418
借酒劲吻你
借酒劲吻你 2020-11-22 11:05

In C/C++, what an unsigned char is used for? How is it different from a regular char?

17条回答
  •  鱼传尺愫
    2020-11-22 11:33

    Because i feel it's really called for, i just want to state some rules of C and C++ (they are the same in this regard). First, all bits of unsigned char participate in determining the value if any unsigned char object. Second, unsigned char is explicitly stated unsigned.

    Now, i had a discussion with someone about what happens when you convert the value -1 of type int to unsigned char. He refused the idea that the resulting unsigned char has all its bits set to 1, because he was worried about sign representation. But he don't have to. It's immediately following out of this rule that the conversion does what is intended:

    If the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. (6.3.1.3p2 in a C99 draft)

    That's a mathematical description. C++ describes it in terms of modulo calculus, which yields to the same rule. Anyway, what is not guaranteed is that all bits in the integer -1 are one before the conversion. So, what do we have so we can claim that the resulting unsigned char has all its CHAR_BIT bits turned to 1?

    1. All bits participate in determining its value - that is, no padding bits occur in the object.
    2. Adding only one time UCHAR_MAX+1 to -1 will yield a value in range, namely UCHAR_MAX

    That's enough, actually! So whenever you want to have an unsigned char having all its bits one, you do

    unsigned char c = (unsigned char)-1;
    

    It also follows that a conversion is not just truncating higher order bits. The fortunate event for two's complement is that it is just a truncation there, but the same isn't necessarily true for other sign representations.

提交回复
热议问题