Changing Numeric Base
Our numbering system is decimal, or "base 10." This means that a number like 527
is equal to (5*100 + 2*10 + 7*1).
A D V E R T I S E M E N T
The use of 10 for the numeric base is a
completely arbitrary decision. It no doubt has something to do with the fact
that most people have 10 fingers (including thumbs). The Babylonians used base
60, which is where we got saddled with the concept of 60 minutes in an hour.
Computer hardware uses base 2, or "binary". A computer number like 1101 is equal
to (1*8 + 1*4 + 0*2 + 1*1). If you add these up, you get 8+4+1=13 . A 10 in
binary is (1*2 + 0*1), or 2. Likewise 10 in any base N is N .
Forth makes it very easy to explore different numeric bases because it can
work in any base. Try entering the following:
DECIMAL 6 BINARY .
1 1 + .
1101 DECIMAL .
Another useful numeric base is hexadecimal. which is base 16. One problem
with bases over 10 is that our normal numbering system only has digits 0 to 9.
For hex numbers we use the letters A to F for the digits 10 to 15. Thus the hex
number 3E7 is equal to (3*256 + 14*16 + 7*1). Try entering:
DECIMAL 12 HEX . \ print C
DECIMAL 12 256 * 7 16 * + 10 + .S
DUP BINARY .
A variable called BASE is used to keep track of the current numeric base.
The words HEX , DECIMAL , and BINARY work by changing this
variable. You can change the base to anything you want. Try:
7 BASE !
6 1 + .
BASE @ . \ surprise!
You are now in base 7 . When you fetched and printed the value of BASE, it said
10 because 7, in base 7, is 10.
PForth defines a word called .HEX that prints a number as hexadecimal
regardless of the current base.
You could define a word like .HEX for any base. What is needed is a way to
temporarily set the base while a number is printed, then restore it when we are
through. Try the following word:
: .BIN ( N -- , print N in Binary )
BASE @ ( save current base )
2 BASE ! ( set to binary )
SWAP . ( print number )
BASE ! ( restore base )