Negative assigned to the trap of unsigned

Has anyone tried to assign a negative number unsigned integer variables? Do you know what this will happen? Let us not try to explore the hidden secrets unsigned integer under.

Let's look at the code below:

int main()
{
      unsigned int val = -1;
      cout<<val<<endl;

      return 0;
}

Execution of results:

4294967295
Press any key to continue...

 

----------------------------------------

You could not help but wonder: so much! I did not expect it, to a negative number for an unsigned integer variable, will have such a big number! why? Well, we have a step by step analysis:

First, careful observation output 4,294,967,295 4,294,967,295 found = 2 ^ 32-1, oh! It seems a bit laws! However, and why this is so? Let us first discuss the manifestation under int and unsigned int, where they are both 4-byte, 32-bit binary representation, but there was a sign bit int, unsigned no. That type int -1 expressed as 1,000,000,000,000,000 0,000,000,000,000,001, then cast it into unsigned int should be 1,000,000,000,000,000 0,000,000,000,000,001 (red is the sign bit), is represented by an index 31 ^ 2 + 1, not 2 ^ 32-1! This is how it happened? (* ^ __ ^ *) hee hee ......, there is also a hidden little secret! Int that in the original code in the memory value is not a true binary storage, but its complement (for ease of calculation, refer to "Digital Logic")! Before then cast, int -1 variables are stored in memory 1,111,111,111,111,111 1,111,111,111,111,111, equal to 2 ^ 32-1. When strong soso into unsigned int, is to read the value of the block of memory assigned to the variable! Such val becomes 4,294,967,295 super large number of! So my colleagues in dealing with unsigned int assignment must be careful! If an error occurs will be a great impact, because unsigned int type usually used as identification for or while loop, if the negative value assigned to it, will lead to serious suspended animation loop! Tongzai! Tongzai!

 

Away from the trap, cherish life! O (∩_∩) O ~ ha

Published 29 original articles · won praise 3 · Views 3178

Guess you like

Origin blog.csdn.net/qq_38436175/article/details/104033725