What is binary?
Binary is the base 2 number system. It uses only two digits, 0 and 1, called bits. Computers use it because electronic circuits can reliably be in one of two states, on or off, and each state can stand for one bit.
Place values
In decimal, each place is worth ten times the one to its right. In binary, each place is worth two times the one to its right: 1, 2, 4, 8, 16, 32, 64, 128 and so on. The binary number 1011 means 8 + 0 + 2 + 1 = 11.
Counting from 0 to 15
0 0000 4 0100 8 1000 12 1100
1 0001 5 0101 9 1001 13 1101
2 0010 6 0110 10 1010 14 1110
3 0011 7 0111 11 1011 15 1111Bits, nibbles and bytes
A group of 4 bits is a nibble. A group of 8 bits is a byte, which can hold 256 different values, from 0 to 255.
Converting
- Binary to decimal: add the powers of 2 where there is a 1. Try the binary to decimal converter.
- Decimal to binary: divide by 2 and read the remainders upward. Use the decimal to binary converter.
- Binary and hex: every hex digit is four bits. See binary to hex and hex to binary.
Negative numbers: two's complement
Most computers store signed integers in two's complement. To negate a number, flip all its bits and add 1. The top bit then acts as a sign: in 8 bits, 11111111 is -1 and 10000000 is -128.
Binary arithmetic
Addition follows four rules: 0 + 0 = 0, 0 + 1 = 1, 1 + 1 = 10 and 1 + 1 + 1 = 11, carrying like decimal addition. Programmers also use bitwise operations: AND, OR, XOR and NOT work on each bit, and shifts move bits left or right, which multiplies or divides by 2.
Binary in code
# Python
print(bin(13)) # 0b1101
print(int("1101", 2)) # 13
print(hex(0b11010110)) # 0xd6
// JavaScript
console.log(0b1101); // 13
console.log((13).toString(2)); // 1101
console.log(parseInt("1101", 2)); // 13Convert instantly. Switch between binary, hex and decimal, with the working shown.