CS 240 Data Structures Binary Representations Binary is
CS 240: Data Structures Binary Representations
Binary is a numerical system that is used to represent numeric values. l Unlike decimal (our traditional method of numeric representation), binary has only two digits: 0 and 1 (instead of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9). l
Counting l l l l l Binary 0 1 10 11 100 101 110 111 l l l l l Decimal 0 1 2 3 4 5 6 7
Counting To translate into decimal: l Take each digit: l l Multiply the rightmost digit by 1. l Multiply the next rightmost digit by 2. l Multiply the next rightmost digit by 4. l And so on.
Conversion Consider 111: l The rightmost digit is 1. 1 * 1 = 1 l The next is 1, 1 * 2 = 2 l The next is 1, 1 * 4 = 4 l The sum of these is 7. l
l 1 Consider 1000 1100 (we usually group binary numbers every 4 digits) 0 0 1 1 0 0 *128 *64 *32 *16 *8 *4 *2 *1 =128 =0 =0 =0 =8 =4 =0 =0 l 0 The sum is: 140
l l Lets turn 555 to binary. int test = 555; while(test != 0) { l l l if test is odd: print 1 else: print 0 test = (int)(test / 2); } This gives us the binary result – but backwards
l l l 555, is odd: 277, is odd: 138, is even: 69, is odd: 34, is even: 17, is odd: 8, is even: 4, is even: 2, is even: 1, is odd: 0 -> done l l l 1 1 0 1 0 0 0 1 1101010001 – in reverse!
1 0 0 0 1 0 1 1 *512 *256 *128 *64 *32 *16 *8 *4 *2 *1 512 1 0 0 0 32 0 Sum = 512 + 32 + 8 + 2 + 1 = 555 8 0 2
- Slides: 9