Intro

Computers store all information using binary, a base-2 numbering system using only 0 and 1.

  • Each digit in binary is called a bit (binary digit).

Unsigned and Signed Integers

Unsigned Integers

  • Only represent non-negative numbers.
  • Maximum value depends on the number of bits:
| Bytes | Type     | Bits | Min Value | Max Value                  |
| ----- | -------- | ---- | --------- | -------------------------- |
| 1     | `uint8`  | 8    | 0         | 255                        |
| 2     | `uint16` | 16   | 0         | 65,535                     |
| 4     | `uint32` | 32   | 0         | 4,294,967,295              |
| 8     | `uint64` | 64   | 0         | 18,446,744,073,709,551,615 |

Signed Integers

  • Can represent negative numbers, usually using two’s complement.
  • Max and min values:
| Bytes | Type  | Bits | Min Value                  | Max Value                 |
| ----- | ----- | ---- | -------------------------- | ------------------------- |
| 1     | int8  | 8    | -128                       | 127                       |
| 2     | int16 | 16   | -32,768                    | 32,767                    |
| 4     | int32 | 32   | -2,147,483,648             | 2,147,483,647             |
| 8     | int64 | 64   | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
 

Converting Between Binary and Decimal

Binary NumberDecimal NumberHex Number
000
111
1022
1133
10044
10155
11066
11177
100088
100199
101010A
101111B
110012C
110113D
111014E
111115F
100001610
100011711
100101812
100111913
101002014
101012115
101102216
101112317
110002418
110012519
11010261A
11011271B
11100281C
11101291D
11110301E
11111311F
1000003220
10000006440
1000000012880
11111111*255FF
100000000256100

Notes:

  • Binary is the fundamental representation for all data in computers
  • Hexadecimal (base-16) is often used as a shorthand for binary because 4 bits = 1 hex digit.

*See Worked Example: Hex ↔ Binary ↔ Decimal for a full 8-bit conversion.

Decimal → Binary

  • Divide the decimal number by 2 repeatedly, writing down the remainder each time.
  • The binary number is the remainders read from bottom to top.

Example: Convert 13 to binary:

 
13 ÷ 2 = 6 remainder 1
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1
Binary: 1101
 

Binary → Decimal

  • Multiply each bit by 2^(position from right, starting at 0) and sum them.

Example: Convert 1101 to decimal:

 
1*2^3 + 1*2^2 + 0*2^1 + 1*2^0 = 8 + 4 + 0 + 1 = 13