Unsigned integer wrapping mechanism and principle analysis in c++

Unsigned integer wrapping mechanism and principle analysis in c++

Recently, I was revisiting c++primer, and by the way, I was training my ability to write a blog. I thought I would graduate soon, and I was hesitating between java and c++ in terms of job hunting. After thinking about it, I still think that c++ is a language for making wheels after all, so study hard~

1. About the unsigned integer wrapping mechanism

#include <iostream>
using namespace std;

int main()
{
  // cout << "Hello World"<<endl;
   unsigned a1 = 10,a2 = 20;
	cout<<"a1-a2="<<a1-a2<<endl;  // a1-a2=4294967286
	cout<<"a2-a1="<<a2-a1<<endl; // a2-a1=10
	
	cout<<"unsigned -1  =  "<<unsigned(-1)<<endl;// unsigned -1  =  4294967295

   return 0;
}

This problem is simple and simple, and it is also disgusting. If it appears in a for loop, then the infinite loop may not find the problem.

Look at the last line of code first, the conversion of -1 (int type) to unsigned type is 4294967295, this strange book is actually 2 to the 32nd power minus 1, because the int type is 32 bits, the same a1-a2 = 4294967286 is 2 to the 32nd power minus 10.

What caused it? This starts with the computer's encoding method: original code, inverse code, and complement code.

2. Original code, inverse code, complement code

First of all, it is clear that inside the computer, all signed data is represented by two's complement, so why is it represented by two's complement?

We know: the representation method of the original code: the highest bit is used as the sign bit, does not represent data, 0 is positive, 1 is negative.
For example [+1] = [0000 0001] (original code) [-1] = [1000 0001] (original code)

Inverse code: positive number is the same as the original code, negative number: the sign bit remains unchanged, and the rest of the digits are inverted
[+1] = [0000 0001] (inverse code) [-1] = [1111 1110] (inverse code)

Complementary code: the positive number is the same as the original code, negative number: the sign bit remains unchanged, and the rest of the digits are inverted +1
[+1] = [0000 0001] (complement code) [-1] = [1111 1111] (complement code)

So here, it basically comes out, -1 for signed type (take 8 bits as an example), the complement code representation is naturally 1111 1111
For unsigned integers, the highest bit does not indicate the sign bit, so it means 255 This is also the principle of the unsigned wrapping mechanism. In the final analysis, it is still the underlying representation of the computer

For the reason why complement code is used and the arguments related to complement code, refer to the blog of this big guy, which is very well written. Portal

Guess you like

Origin blog.csdn.net/qq_42190158/article/details/113129699