In C/C++, what an unsigned char
is used for? How is it different from a regular char
?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
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 tounsigned char
. He refused the idea that the resultingunsigned 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: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 resultingunsigned char
has all itsCHAR_BIT
bits turned to 1?UCHAR_MAX+1
to-1
will yield a value in range, namelyUCHAR_MAX
That's enough, actually! So whenever you want to have an
unsigned char
having all its bits one, you doIt 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.
unsigned char is the heart of all bit trickery. In almost ALL compiler for ALL platform an unsigned char is simply a BYTE. An unsigned integer of (usually) 8 bits. that can be treated as a small integer or a pack of bits.
In addiction, as someone else has said, the standard doesn't define the sign of a char. so you have 3 distinct "char" types: char, signed char, unsigned char.
unsigned char
takes only positive values....like 0 to 255where as
signed char
takes both positive and negative values....like -128 to +127quoted frome "the c programming laugage" book:
The qualifier
signed
orunsigned
may be applied to char or any integer. unsigned numbers are always positive or zero, and obey the laws of arithmetic modulo 2^n, where n is the number of bits in the type. So, for instance, if chars are 8 bits, unsigned char variables have values between 0 and 255, while signed chars have values between -128 and 127 (in a two' s complement machine.) Whether plain chars are signed or unsigned is machine-dependent, but printable characters are always positive.