BaseConversion

Download Report

Transcript BaseConversion

Base Conversion
Number bases
Digital
computers usually store
integers in base 2 (binary), base 8
(octal), or base 16 (hexadecimal)
26610 = 1000010102 = 4128 = 10A16
Arbitrary Bases
In
base 2, we only need 2 digits, 0,1.
In base 16, we need 16 digits
Use the letters "ABCDEF" to
represent the digits from 10 to 15.
With enough digits, integers can be
expressed in any base!
Other interesting bases
Base
36.
0123456789ABCDEFGHIJKLMNOPQR
STUVWXYZ
Base 51.
0123456789ABCDEFGHIJKLMNOPQR
STUVWXYZabcdefghijklmnopqrstuvw
xyz+-*/=()!@#$%^&_
Some interesting numbers
4011 (10->16)
57005 (10->16)
1767707668033969
(10->36)
7194 (10->51)
31071116227 (10->51)
GQE8RABO5H0JZQGTD709CK
(36 -> 51)
FAB
DEAD
HELLOWORLD
2/3
1/2=2/4
This_is_not_a_number
Convert one base to another
1.
2.
3.
4.
5.
Convert base 16 to base 10.
Convert any base to base 10.
Convert base 10 to base 16
Convert base 10 to any base.
Combine Steps 2 and 4.
1. Base 16 to base 10
Represent
Base 16 numbers as
strings.
Digits in Base 16:
digits = '0123456789ABCDEF'
digits.find('F') = 15
(15 is base 10 equivalent of digit 'F')
Example
In
Base 16: 20A = 20*10 + A
In Base 10: 522 = 32*16 + 10
If we had a subroutine to convert
hex to decimal, this equation would
read:
 decimal(20A) =
decimal(20)*16 + decimal(A)
Code for base 16 to 10
def deciamal(s):
d = '0123456789ABCDEF'
if len(s) == 1:
return d.find(s)
else:
return decimal(s[:-1])*16 + d.find(s[-1])
2: Any Base to 10
def decimal(s,d):
b = len(d)
if len(s) == 1:
return d.find(s)
else:
return decimal(s[:-1],d)*b + d.find(s[1])
3. Base 10 to 16
Think
of 522 = a2162 + a116 + a0
Then a2a1a0 is the hexadecimal
representation of 522.
Clearly 522%16 = a0
Also 522//16 = a216 + a1 = (a2a1) 16
Code decimal to hex
def hex(n):
d = '0123456789ABCDEF'
if n < 16:
return d[n]
else:
return hex(n//16) + d[n%16]
4. Code decimal to any base
def anyBase(n,d):
b = len(d)
if n < b:
return d[n]
else:
return anyBase(n//b,d) + d[n%b]
5. Any base to any base
def changeBase(s,digits0,digits1):
n = decimal(s,digits0)
t = anyBase(n,digits1)
return t
More usable:
def defaultDigits(n):
d = '01234567890ABCDEFGHI' + \
'JKLMNOPQRSTUVWXYZ' + \
'abcdefghijklmnopqrstuvwxyz'+\
'+-*/!@#$%^&()_'
return(d[:n])
5'. Base to Base
def base2base(s,a,b):
d0 = defaultDigits(a)
d1 = defaultDigits(b)
return anyBase(decimal(s,d0),d1)