In C, the default basic data type is signed. Now we take char as an example to illustrate the difference between (Signed) Char and unsigned char.
First of all, in the memory, char is no different from unsigned char, It is a byte, the only difference is that the highest bit of char is a symbol bit, so char can represent-128 ~ 127, unsigned char has no sign bit, so it can represent 0 ~ 255. It is easy to understand that 8 bits can be used in a maximum of 256 cases. Therefore, 256 digits can be expressed in any case.
What are the differences in actual use?
It is mainly a symbol bit, but in normal assignment, there is no difference between reading and writing files and network byte streams. It is a byte. No matter what the highest bit is, the final reading result is the same, it's just how you understand the highest bit. The display on the screen may be different.
However, we found that all bytes use unsigned char. Why?
First of all, we generally understand that byte has no symbol bit. More importantly, if the value of byte is assigned to data types such as int and long, the system will do some additional work.
If it is Char, the system considers the highest bit as the sign bit, And the int may be 16 or 32 bits, then the maximum bit will be extended (note that the value assigned to the unsigned int will also be extended)
If it is an unsigned char, it will not be extended.
This is the biggest difference between the two.
Similarly, it can be deduced to other types, such as short and unsigned short. And so on.
For more information, see the following small example.
Include <stdio. h>
Void F (unsigned char V)
{
Char c = V;
Unsigned char UC = V;
Unsigned int A = C, B = UC;
Int I = C, j = UC;
Printf ("---------------- \ n ");
Printf ("% C: % C, % C \ n", C, UC );
Printf ("% x: % x, % x \ n", C, UC );
Printf ("% u: % u, % u \ n", a, B );
Printf ("% d: % d, % d \ n", I, j );
}
Int main (INT argc, char * argv [])
{
F (0x80 );
F (0x7f );
Return 0;
}
Output result:
----------------
% C :?, ?
% X: ffffff80, 80
% U: 4294967168,128
% D:-128,128.
----------------
% C :,
% X: 7f, 7f
% U: 127,127
% D: 127,127
It can be seen that if the highest bit is 0, there is no difference between the two. If it is 0, there is a difference.