CS253: Software Development with C++

Spring 2022

Bases

Show Lecture.Bases as a slide show.

CS253 Bases

Bases

Writing integers (mathematics)

Writing integers (C++ source code)

0b… or 0B…
It’s binary, base 2.
0x… or 0x…
It’s hexadecimal (“hex”), base 16. “Hexa” is Greek, “decimal” is Latin. 😼
0digits
It’s octal (base 8). Plain 0 is octal, not decimal!
Otherwise
It’s decimal (base 10). “Decimal” ≠ “digits after the decimal point” here.

Write for readability: sizes in decimal, bitmasks in binary, octal, or hex.

cerr << 0b11 << ' ' << 0XfF << ' ' << 012 << ' ' << 34;
3 255 10 34

Place notation

Consider an ordinary, three-digit base 10 number. It has a hundreds place, a tens place, and a ones place. You know this so well that you’ve forgotten it.

So, 78910 means:

Place notation

Now, consider a base 8 number, such as 3758. This means:

Place notation

A binary number, such as 1 01102, means:

Place notation

Of course, in practice, we wouldn’t bother writing down the terms with zero coefficients, since they contribute only zeroes to the sum.

A binary number, such as 1 01102, means:

I’m thinking of a number…

0644 in octal… okayyyyyy…

What is 0644 in decimal?

What is 0644 in binary?

Hardest way is convert to decimal, then convert to binary.

What is 0644 in hexadecimal?

DecimalHex
00
11
22
33
44
55
66
77
88
99
10a
11b
12c
13d
14e
15f

What is 0644 in hexadecimal?

Why doesn’t the easy way always work?

It’s all about the ratios:

FromToRatioHard?
OctalBinary8 = 23Easy
HexadecimalBinary16 = 24Easy
HexadecimalOctal16 = 8log₈16 = 84/3OK
HexadecimalDecimal16 = 10log₁₀16 = 101.20412Hard
DecimalOctal10 = 8log₈10 = 81.1073Hard
DecimalBinary10 = 2log₂10 = 23.3219Hard

Everything’s simple, unless stupid decimal (🖐🖑) is involved.

So, our number is:

1 1010 01002 or 6448 or 42010 or 1a416

The computer doesn’t care!

cout << 0b10000 << ' ' << 020 << ' ' << 16 << ' ' << 0x10 << '\n';
16 16 16 16

How does it know?

It doesn’t know—you have to tell it!

int x = 0b10101;
cout << x << '\n'
     << oct << x << '\n'
     << hex << x << '\n'
     << dec << x << '\n';
21
25
15
21