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-127 ~ 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.
The biggest difference between the two is: But we found that when the byte is expressed, the unsigned char is used. 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. If the highest bit is 0, there is no difference between the two. If it is 1, there is a difference. Similarly, it can be deduced to other types, such as short, 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;
}
The output is as follows:
Result Analysis:
For (Signed) Char, the value 0x80 is expressed as 1000 0000 in binary format. When it is assigned to the unsigned Int or Int as a char, the system considers the highest bit as the symbol bit and expands the highest bit. 0x7f is represented as 0111 1111 in binary format, and the highest bit is 0, which is not extended.
For unsigned char, no extension is made whether the maximum bit is 0 or 1.