One's complement.
Two's complement - radix complement.
Visually represented by a number line.
100 101 110 111 000 001 010 011 3 bit storage 2^3 = 8 values
-4 -3 -2 -1 0 1 2 3
High bit still acts as a flag to indicate negative value.
Requires the working storage/word to be a known constant size.
Generating the binary of a negative in 2s complement.
Technique :
Know the bit size of the number storage/word size, use all bits.
Using the unsigned binary representation of the value
Flip (complement) ALL bits in number.
Add one.
Example: convert 3 to -3 using 16 bit storage.
3 = 0000 0000 0000 0011b Note for conversion, use all bits.
1111 1111 1111 1100b Flip
+ 1b Add 1
-------------------
1111 1111 1111 1101b 2s complement.
Similar to 1's complement except value is adjusted when first
stored.
Machines that support separate 8, 16, and 32 bit numbers at hardware level
Have distinct instructions or arguments for each number size to guarantee
correct propagation of sign bit and overflow detection.
Convert -117 to binary.
Calculate the binary representation of the absolute value
117 MSB
58 r 1 LSB 117 - 64 * 1 = 53
29 r 0 53 - 32 * 1 = 21
14 r 1 21 - 16 * 1 = 5
7 r 0 5 - 8 * 0 = 5
3 r 1 5 - 4 * 1 = 1
1 r 1 1 - 2 * 0 = 1
0 r 1 MSB 1 - 1 * 1 = 0
1110101 64+32+16+4+1 = 117
(64*1+32*1+16*1+8*0+4*1+2*0+1*1)
Left pad with zeros to recognized integer size, using 16-bit number.
00000000 01110101
Flip bits.
11111111 10001010
Add one.
11111111 10001011 -117 (65536 - 117 = 65419)
00000000 00000000
- 01110101
-------------------
11111111 10001011
If given a signed binary value and its high bit set indicating negative
value, to find the absolute value, use same process.
Complement (flip) all bits.
Add 1
Most negative value has to be handed special. Calculating the inverse of
-128 (8-bit).
1000 0000
0111 1111 flip
+ 1 add 1
--------------
1000 0000 End up with -128.
Solution, test special or use larger representation.
Overflow.