int32 storage in memory [duplicate]

徘徊边缘 提交于 2019-12-05 22:14:07

Only one bit is used for sign (negative or positive)

Int32 values are represented in 31 bits, with the thirty-second bit used as a sign bit. Positive values are represented by using sign-and-magnitude representation. Negative values are in two's complement representation, MSDN

Int32.MaxValue =  2^31 - 1 = 01111111111111111111111111111111                
Int32.MinValue = -2^31     = 10000000000000000000000000000000

I have found nice article to understand the two's complement here.

Conversion from Two's Complement

Use the number 0xFFFFFFFF as an example. In binary, that is:

1111 1111 1111 1111 1111 1111 1111 1111

What can we say about this number? It's first (leftmost) bit is 1, which means that this represents a number that is negative. That's just the way that things are in two's complement: a leading 1 means the number is negative, a leading 0 means the number is 0 or positive.

To see what this number is a negative of, we reverse the sign of this number. But how to do that? To reverse the sign you simply invert the bits (0 goes to 1, and 1 to 0) and add one to the resulting number.

The inversion of that binary number is, obviously:

0000 0000 0000 0000 0000 0000 0000 0000

Then we add one.

0000 0000 0000 0000 0000 0000 0000 0001

So the negative of 0xFFFFFFFF is 0x00000001, more commonly known as 1. So 0xFFFFFFFF is -1.

Conversion to Two's Complement

Note that this works both ways. If you have -30, and want to represent it in 2's complement, you take the binary representation of 30:

0000 0000 0000 0000 0000 0000 0001 1110

Invert the digits.

1111 1111 1111 1111 1111 1111 1110 0001

And add one.

1111 1111 1111 1111 1111 1111 1110 0010

Converted back into hex, this is 0xFFFFFFE2

Edit, How does CPU performs subtraction using Two's complement

The CPU performs the subtraction using addition on two's complement of negative number. Lets take an example of 8 bit numbers. We want to subtract 4 from seven.

7 = 00000111
4 = 00000100
Two' complement of 4

Step 1 take inverse of 00000100 by converting 0 to 1 and 1 to 0

00000100 -> 11111011

Step 2 Add one to inverse

11111011
00000001
========
11111100

7- 4 = 7 + (Two's complement of 4)

00000111 (binary representation of 7)
11111100 (binary representation after Two's complement of 4)
========
00000011  (binary representation of 3)    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!