The knowledge gap left by C\C++ inadvertently------signed numbers and unsigned numbers

C and C++

C and C++ should be the first two languages ​​that most engineering students come into contact with. I personally feel that these two languages ​​are quite difficult. When I was looking at the interview questions today, I was stunned when I saw signed and unsigned numbers. How weak the foundation is!

Signed and unsigned numbers

For floating-point numbers, all are signed numbers, and there is no unsigned number. So let's take the char type of 8 bits and one byte to talk about the signed and unsigned numbers.
First of all, we know that for unsigned numbers: if it is 8 bits, the maximum representation is 255.
For example: 0000 0001 = 1
1111 1111 = 255.
For signed numbers, I think many people know that the first bit represents the sign bit, and I have forgotten how to express it later. I just I forgot about this, it took me a long time to figure it out.
The first digit is 1 for negative numbers, and the first digit is 0 for positive numbers
Example: Then -7, I think some of them are expressed like this1000 0111, sorry I started like this, but it's not right.
Remove the sign bit, then add one to the bitwise inversion. This is how to express a negative number.
Take -7 as an example. The first step is: 1000 0111. The second step is the bitwise inversion: 1111 1000. The third step is to add one: 1111 1001
so -7 = 1111 1001
-8 > 1000 1000 > 1111 0111 > 1111 1000

At the same time, there is another point that adding an unsigned number and a signed number will automatically convert to an unsigned number.
Let's operate -7+7 = 1111 1001 + 0000 0111 = 1 0000 0000. There are only eight bits, overflow, and the result is 0. In line with our knowledge -7+7 = 0. Let's operate -8 + 7 =
1111 1000 + 0000 0111 = 1111 1111 = 255 This is different from our common sense. Need to pay attention when programming.
insert image description here
In the process of programming, try not to directly operate unsigned numbers and signed numbers. Because default type conversion will occur in the middle.
insert image description here

Guess you like

Origin blog.csdn.net/qq_25105061/article/details/108219634