The Department of Computer Science & Engineering
|
|
STUART C. SHAPIRO: CSE
115 C
|
Using bits to represent integers:
| Binary | Decimal |
| 000 | 0 |
| 001 | 1 |
| 010 | 2 |
| 011 | 3 |
| 100 | 4 |
| 101 | 5 |
| 110 | 6 |
| 111 | 7 |
Positional notation
Decimal: ones, tens, hundreds, ...
Binary: ones, twos, fours, ...
Octal: ones, eights, sixtyfours, ...
Hexadecimal: ones, sixteens, two hundred fiftysixes, ...
The two binary digits: 0, 1
The eight octal digits: 0, 1, 2, 3, 4, 5, 6, 7
The ten decimal digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
The fifteen hexadecimal digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b,
c, d, e, f
For conversion:
If divide a number n by a base
b, the remainder is the right-most digit, and the result is the
rest of the number.
Examples: 3597/10 = 359 R7 11011/2 = 1101 R1
It works even if n is not expressed in base b:
So 10352 = 10 000 001 0111035 / 2 = 517 R 1 517 / 2 = 258 R 1 258 / 2 = 129 R 0 129 / 2 = 64 R 1 64 / 2 = 32 R 0 32 / 2 = 16 R 0 16 / 2 = 8 R 0 8 / 2 = 4 R 0 4 / 2 = 2 R 0 2 / 2 = 1 R 0 1 / 2 = 0 R 1
With 7 bits, can represent 128 numbers, e.g. 0, ..., 127.
But what about negatives: -0, ..., -127?
First idea (sign + magnitude):
3 = 00000011 0 = 00000000 -3 = 10000011 -0 = 10000000Bad idea: addition is different; -0 is wasteful.
Second idea (biased):
use 00000000 for -127, 11111111 for 128.
That is, to represent n, use binary representation of 127 +
n.
3 = 10000010 0 = 01111111 -3 = 01111100 -0 = 01111111Problem: 3 + -3 = 254. But see below:
Better idea: Two's Complement
To go from n to -n: complement bits, add 1, drop final carry
0 = 00000000 1 = 00000001 3 = 00000011 4 = 00000100 7 = 00000111
complement 11111111 11111110 11111100 11111011 11111000
add 1 0 = 00000000 -1 = 11111111 -3 = 11111101 -4 = 11111100 -7 = 11111001
No -0, and it's reversible.
n + -n 00000000 00000000 00000000 00000000 00000000
4 = 00000100 -3 = 11111101
-1 = 11111111 -4 = 11111100
-------- --------
sum 00000011 = 3 sum 11111001 = -7
Retrieve decimal fractional digits by repeated multiplication by 10.
.32054
3.2054
2.054
0.54
5.4
4.
So retrieve binary fractional bits by repeated multiplication by 2.
.1101
1.101
1.01
0.1
1.
Even if "bits" are in decimal notation.
.25
0.5
1.
So, .2510 = .012
Try 0.110:
.1
0.2
0.4
0.8
1.6
1.2
0.4 repeat...
So, .110 = .0001100110011...2
1. ...
(4.9e-324 + 0.0)/2