Understanding Binary and Hexidecimal
Posted on 01-08-2007, by Tim
Understanding Binary
The number system you are probably most familiar with is decimal. It has ten (hence the name) different digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. As you begin counting past 9, you should recall quite quickly that a second digit is also used: 10.

What is 10? Mathematically, it is 1 * 10^1 + 0 * 10^0 which would be 10 + 0. For example, 57,803 would be 5 * 10^4 + 7 * 10^3 + 8 * 10^2 + 0 * 10^1 + 3 * 10^3, or 50000 + 7000 + 800 + 3.

Decimal is referred to as base ten because it has ten units in its representation. However, computers do not naturally interpret base 10, they natively work in base 2, or binary.

Binary representation only has two characters, 0 and 1. Here is a table of some binary numbers to 4 binary digits and their decimal equivalents:

 Code: Binary | Decimal 0000   | 0 0001   | 1 0010   | 2 0011   | 3 0100   | 4 0101   | 5 0110   | 6 0111   | 7 1000   | 8 1001   | 9 1010   | 10 1011   | 11 1100   | 12 1101   | 13 1110   | 14 1111   | 15

Since computers are limited by memory, binary digits, or bits, need to be explicitly expressed. The decimal system is different in this case. If a number has to extend to the hundred thousands, then so be it. But 010 and 0010, while both having the decimal value of 2, are being represented in different bits. If you're working in 3 bit representation, you can only deal with binary numbers in 3 bit representation, no more, no less.

2s Complement System in Binary
2s compliment is the system that is currently used by all computers to perform arithmetic at the lowest level. Negative numbers have a '1' as the most significant bit (the left-most bit), and positive numbers have a '0' as the most significant bit. To convert a positive number to a negative number, invert all of the bits. (0s become 1s, 1s become 0s). Then add 1. (0101 [5] becomes 1010. Then 1 is added to 1010 to become 1011 [-5]).

2s complement's range is from -2^(n-1) to 2^(n-1)-1 where n is the number of bits you are using. Here's a table of a 5-bit representation of 2s complement:

 Code: 2s Complement Binary | Decimal 00000                | 0 00001                | 1 00010                | 2 00011                | 3 00100                | 4 00101                | 5 00110                | 6 00111                | 7 01000                | 8 01001                | 9 01010                | 10 01011                | 11 01100                | 12 01101                | 13 01110                | 14 01111                | 15 10000                | -16 10001                | -15 10010                | -14 10011                | -13 10100                | -12 10101                | -11 10110                | -10 10111                | -9 11000                | -8 11001                | -7 11010                | -6 11011                | -5 11100                | -4 11101                | -3 11110                | -2 11111                | -1