Skip to content

Latest commit

 

History

History
59 lines (38 loc) · 1.64 KB

4.5.4.3 Signed binary using two’s complement.md

File metadata and controls

59 lines (38 loc) · 1.64 KB

Two's Complement

Know that signed binary can be used to represent negative integers and that one possible coding scheme is two’s complement.

Computers need to be able to represent negative numbers as well as positive numbers and thats where signed binary helps. One possible way to sign binary numbers is using two's complement.

Using two's complement

Know how to:

  • represent negative and positive integers in two’s complement
  • perform subtraction using two’s complement
  • calculate the range of a given number of bits, n.

Representation

When using two's complement, the most significant bit is signed as negative. For example the MSB of an 8 bit binary number would not be 128 it would be -128. All other bits are still positive.

Making a positive binary number negative

  1. Invert all bits, making 0->1 and 1->0
  2. Add one to the number

Example

Make 57 negative.

  1. 57 in binary is 0 0 1 1 1 0 0 1
  2. Invert all bits: 1 1 0 0 0 1 1 0
  3. Add one: 1 1 0 0 0 1 1 1
  4. Check: (-128) + 64 + 4 + 2 + 1 = -57

Subtractions

Since computers cannot subtract two positive numbers easily, they can make one negative and then perform addition.

Example

Perform 63 - 57

  1. 67 in binary is: 0 0 1 1 1 1 1 1
  2. 57 in binary is: 0 0 1 1 1 0 0 1
  3. -57 in two's complement is: 1 1 0 0 0 1 1 1
  4. Perform addition: 1 0 0 0 0 0 1 1 0
  5. Reduce down into original number of bits, in this case 8 so remove the leading 1.
  6. Check: 0 0 0 0 0 1 1 0 in decimal is 6, 63 - 57 = 6

Range

The range for two's complement for n bits is:

-2n-1 to 2n-1-1

Example

Where n is 8, the range is -128 to 127