Home / Encoding guides / Guide: binary numbers

Binary Numbers Explained

A clear introduction to base 2: how it works, how to convert it, and why computers use it.

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 1111

Bits, 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

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));     // 13

Convert instantly. Switch between binary, hex and decimal, with the working shown.

Open the binary to hex converter

Frequently asked questions

Why do computers use binary?

Circuits are most reliable with two states, on and off, so each bit is a 0 or a 1.

How many values can a byte hold?

256, from 0 to 255 unsigned, or from -128 to 127 signed.

What is the difference between a bit and a byte?

A bit is one binary digit. A byte is eight bits.