开发者

signed two's complement arithmetic

开发者 https://www.devze.com 2023-02-09 04:14 出处:网络
I was thinking on data types ranges, a question arises. As we know signed char\'s range is from -128 to 127.

I was thinking on data types ranges, a question arises. As we know signed char's range is from -128 to 127. I got the how 127 comes, i.e. 0111111 = +127

B开发者_开发知识库ut I could not get how -128 comes? if we just ON sign bit we get 11111111, how its is equal to -128 ?


Most of the time, computers use what's called 2's complement to represent signed integers.

The way 2's complement works is that the possible values are in a huge loop, from 0, to MAX_VALUE, to MIN_VALUE, to zero, and so on.

So the minimum value is the maximum value +1 - 01111111 = 127, and 10000000 = -128.

This has the nice property of behaving exactly the same as unsigned arithmetic - if I want to do -2 + 1, I have 11111110 + 00000001 = 11111111 = -1, using all the same hardware as for unsigned addition.

The reason there's an extra value on the low end is that we choose to have all numbers with the high-bit set be negative, which means that 0 takes a value away from the positive side.


In two's complement, -128 is 10000000.


Negative numbers have the sign bit set to 1; -128 is the value with the sign bit set but no other bits (i.e., it is the smallest negative number). The binary representation of -128 is 10000000. For other data lengths, the smallest negative number in two's complement is always 1000... for the correct number of zeros.


One simple way to think of this is to start at 01111111 and then keep subtracting 1 until it wraps around; the previous value is the smallest negative value. Subtracting 1 from 00000000 using the standard "borrow" technique yields 11111111, which is indeed the binary representation for -1. We can keep subtracting down to 10000000, which is -128, and subtracting one more yields 01111111 again, wrapping around.

0

精彩评论

暂无评论...
验证码 换一张
取 消