TWO’S COMPLEMENT NOTATION

来源:互联网 发布:windows本地搭建git 编辑:程序博客网 时间:2024/04/28 01:21

Two's complement notation is a way to encode negative numbers into ordinary binary, such that addition still works. Adding −1 + 1 should equal 0, but ordinary addition gives the result of 2 or −2 unless the operation takes special notice of the sign bit and performs a subtraction instead. Two's complement results in the correct sum without this extra step.


To represent a negative number using two’s complement notation:

  1. Start with the binary representation of the positive version of the number.

  2. Complement all the bits (turn the ones into zeros and the zeros into ones).

  3. Add one to the result.


For example, the binary notation for the number 9 is 00001001. To represent –9 in two’s complement notation, flip the bits (11110110) and then add 1. The two’s complement for –9 is 11110110 + 1 = 11110111. The binary notation for the number 2 is 00000010. The two’s complement for –2 would be 11111101 + 1 =11111110.


Don’t worry about the details of binary representation and arithmetic. What’s important to remember is that the computer uses one notation for positive-only numbers and a different notation for numbers that can be positive or negative. Both notations allow a byte to take on one of 256 different values. The positives-only scheme allows values ranging from 0 to 255. The two’s complement scheme allows a byte to take on values ranging from –128 to 127. Note that both of these ranges contain exactly 256 values. If the 2 bytes are unsigned(never allowed to hold a negative value), they can hold values ranging from 0 to 65,535. If the 2 bytes are signed(allowed to hold both positive and negative values), they can hold values ranging from –32,768 to 32,767.






原创粉丝点击