CS 208 s21 — Binary & Hexadecimal
Table of Contents
Sorry for the too-loud audio here, working with a more sensitive webcam than I was used to.
1 Binary & hexadecimal
Many parts of this course will involve thinking about data storage and manipulation at a very low level.
- binary = base 2
- base 10 (regular decimal numbers) has a 1s, 10s, 100s digit, etc.
- the number 23 is \(2\times 10 + 3 \times 1\)
- 1s, 10s, 100s, … can be written as \(10^0\), \(10^1\), \(10^2\), …
- hence base 10 numbers
- binary just substitutes a base of 2 for a base of 10
- \(2^0\), \(2^1\), \(2^2\), …
- 1s, 2s, 4s, …
- the binary number 11 is \(1\times 2 + 1\times 1\) or 3 in base 10
- the base of a numbering system also indicates how many unique digits it has
- base 10 has the digits 0–9, after 9 we carry over to the next larger place
- base 2 has two digits, 0 and 1
- why use base 2 for computing? It's a natural fit with presence/absence of electric current or high vs low voltage
- a single binary digit is called a bit, the fundamental unit of digital data
- it's also very common to talk about data in terms of bytes (8 bits to a byte)
- base 10 (regular decimal numbers) has a 1s, 10s, 100s digit, etc.
- hexadecimal = base 16
- same principle as before
- \(16^0\), \(16^1\), \(16^2\), … \(\rightarrow\) 1s, 16s, 256s
- but why base 16?
- first, base 10 doesn't place nice with binary since 10 isn't a power of 2
- 16 is \(2^4\), giving it the nice property of 4 bits to represent each digit, 2 hex digits to a byte
- a single hex digit, or 4 bits, is called a nybble (little bit of computer scientist humor for you there)
- speaking of hex digits, the 0 to 9 we're used to aren't enough
0x10
(hex numbers indicated with 0x prefix) is 16 in base 10, we need digits for 10–15- use the letters a–f
- same principle as before
base 10 | base 2 | base 16 |
---|---|---|
0 | 0b0000 |
0x0 |
1 | 0b0001 |
0x1 |
2 | 0b0010 |
0x2 |
3 | 0b0011 |
0x3 |
4 | 0b0100 |
0x4 |
5 | 0b0101 |
0x5 |
6 | 0b0110 |
0x6 |
7 | 0b0111 |
0x7 |
8 | 0b1000 |
0x8 |
9 | 0b1001 |
0x9 |
10 | 0b1010 |
0xa |
11 | 0b1011 |
0xb |
12 | 0b1100 |
0xc |
13 | 0b1101 |
0xd |
14 | 0b1110 |
0xe |
15 | 0b1111 |
0xf |
16 | 0b10000 |
0x10 |
- the table above shows how hexadecimal counts up to
0xf
before carrying over to0x10
2 Everything is bits!
An important idea in CS 208 is that all data stored on a computer system is just bits.
What matters is how those bits are interpreted.
In fact, the same bits can take on completely different and equally valid meanings under different interpretations.
For example, consider 0x4e6f21
, what does it mean?
- base 10 integer 5140257
- the characters "No!" (http://www.asciitable.com)
- a nice olive green color (check it out)
- the real number \(7.20303424\times 10^{-39}\)
It's up to the program/programmer to interpret what any sequence of bits actually represents.