Representing Integers in Different Bases

advertisement
Representing Integers in Different Bases
Let b 1 be an integer. We say we have represented the positive integer n in base b , and
write
n (ak ak 1 a1a0 )b
if
n ak bk ak 1bk 1
a1b a0
with
0 a j b 1 for 0 j k , and ak 0
Example 1 We have 19 (201)3 since 19 2 32 0 31 1 30 Similarly, we have 19 (1011)2 ,
since 19 1 24 0 23 0 22 1 2 1 .
Converting From Base 10 to base b
Given a positive integer n expressed in decimal form, that is, in base 10, express n in base b as
follows: Use the division theorem repeatedly.
n
q0 b r0
0 r0
b
q0
q1 b r1
0 r1
b
q1
q2 b r2
0 r2
qk
3
qk
2
b rk
2
qk
2
qk
1
b rk
1
qk
1
0 b rk
0 rk
0 rk
b
b
2
1
0 rk
b
b
This process must end with the quotient being 0 as indicated, because we must have
n q0
q1
q2
qk
1
0.
Then
n
so we have
rk bk
rk 1bk
1
rb
r0
1
n (rk rk
1
rr
1 0 )b .
Example 2 Express 61 in base 2.
61
30
15
7
3
1
30 2 1
15 2 0
7 2 1
3 2 1
1 2 1
0 2 1
Hence,
61 (111101)2 .
Exercises
1. Express 224 in base 3.
2. Express 224 in base 6.
3. Express 7 in base 8
Converting From Base b to base 10
We introduce Horner’s method for evaluating a polynomial. This will then be used to solve the
conversion problem.
Let p( x) ak x k ak 1 x k
the following steps:
1
a1 x1 a0 . The value p(b) can be computed for any value b, by
qk
qk
qk
ak
1
qk b ak
2
qk 1b ak
1
2
(Horner's method)
Then we have
q2
q3b a2
q1
q2b a1
q0
q1b a0
p(b) q0 .
Suppose we have a positive integer n expressed in base b, say
n (ak ak
1
a1a0 )b
The value n will be the result of applying Horner’s method to compute p(b) where
p( x )
ak x k
ak 1 x k
1
a1 x1 a0 .
Exercises
4. Using your favorite computer language, write a function taking as arguments an integer b
and an array of integers {a0 , a1, , ak } and returning the value of p(b) computed by
Horner’s method.
5. Express in decimal form the integer n
(674450026)8 .
6. Let n (67 AF 50D6)16 be an integer in hexadecimal form. Use Horner’s method to express
n in decimal form.
7. Take your answer to 6 and apply our algorithm to express n in hexadecimal form. (You
should recover the base 16 representation given in problem 6.
Download