14.1: Power of 2 and Numbers
- Page ID
- 43743
Let’s start with some simple math. In the digital world, information is encoded as powers of 2. Nothing really new. In Smalltalk raising a number to a power is performed by sending the message raisedTo:
to a number. Here are some examples. Figure \(\PageIndex{1}\) shows the powers of 2.
2 raisedTo: 0 → 1 2 raisedTo: 2 → 4 2 raisedTo: 8 → 256
Using a sequence of powers of 2 we can encode numbers. For example, how can we encode the number 13? It cannot be higher than \( 2^4 \) because \( 2^4 = 16 \). So it should be \( 8 + 4 + 1 \), \( 2^3 + 2^2 + 2^0 \). Now when we order the powers of two as a sequence as shown in Figure \(\PageIndex{2}\), we see that 13 is encoded as 1101. So we can encode a number with a sequence of powers of 2. An element of this sequence is called a bit. 13 is encoded with 4 bits, corresponding to \( 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0 \). This sequence of bits represents a binary notation for numbers. The most significant bit is located on the left of a bit sequence and the least on the right (\( 2^0 \)is the rightmost bit).
Binary notation
Pharo has a syntax for representing numbers in different bases. We write 2r1101
where 2 indicates the base or radix, here 2, and the rest the number expressed in this base. Note that we could also write 2r01101
or 2r0001101
since this notation follows the convention that the least significant bit is the rightmost one.
2r1101 → 13 13 printStringBase: 2 → '1101' Integer readFrom: '1101' base: 2 → 13
Note that the last two messages printStringBase:
and readFrom:base:
do not handle the internal encoding of negative numbers well as we will see later. -2 printStringBase: 2
returns -10 but this is not the internal number representation (known as two’s complement). These messages just print/read the number in a given base.
The radix notation can be used to specify numbers in different bases. Obviously 15 written in decimal base (10r15) returns 15, while 15 in base 16 returns \( 16 + 5 = 21 \) as illustrated by the following expressions.
10r15 → 15 16r15 → 21