I recently encountered a strange problem in Raspberry Pi development.
For example:
Char a = 0x8f;
Printf ("% d", );
We want to get-113, but what we get on Raspberry Pi is 143.
What's going on? Why not scale according to the symbol bit?
Later, I checked the information.
As follows:
Ansi c provides three character types: char, signed char, and unsigned char.
Char is equivalent to signed char or unsigned char, but it depends on the compiler!
These three types of characters are stored in 1 byte, and 256 different values can be saved.
The difference is the value range.
The value range of signed char is-128 to 127.
Unsigned char value range: 0 to 255
The highest bit of signed char is the sign bit, so char can represent-128 ~ 127, unsigned char has no sign bit, so it can represent 0 ~ 255.
But is char equivalent to signed char or unsigned char ??
This is the difference between char and int!
Int = signed int, but char cannot simply think = signed char
Determine what char is equivalent to when testing based on different Compilers
Most machines use supplementary codes to store integers. In these machines, all bits of-1 stored according to the integer type are 1
If my machine is also stored in this way, we can determine whether char is equal to signed char or unsigned char.
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 because byte has no symbol bit.
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.