With integer representation we can define a base. For Base 10, a value of \(531_{10}\) is represented as \(5 \times 10^2 + 3 \times 10^1 + 1 \times 10^0\). With Base 4, a value of \(331_4\) would be defined as \(3 \times 4^2 + 3 \times 4^1 + 1 \times 4^0\) and which is equivalent to \(61_{10}\) in Base 10.
Radix representation |
Method
TFor an integer \(a\) and a radix \(b\):
\(i=0\)
while (\(q < 0\)):
\(\enspace x=q\)
\(\enspace q=\lfloor\frac{x}{b}\rfloor\)
\(\enspace a_i=x-q\lfloor{b}\rfloor\)
\(\enspace i=i+1\)
In this \( \lfloor{b} \rfloor\) is the floor function for \(b\).
Coding
The coding is here:
import math import sys a=31 b=16 def hex(a): if (a<10): res=str(a) else: res=chr(a+55) return(res) if (len(sys.argv)>1): a=int(sys.argv[1]) if (len(sys.argv)>2): b=int(sys.argv[2]) print (f"Value={a} and radix={b}") i=0 x=a q=math.floor(x/b) res=hex(x-q*b) while (q>0): i=i+1 x=q q=math.floor(q/b) a_i=x-q*b res=res+hex(a_i) res=res[::-1] print (res)
A sample run:
Value=3213 and radix=2 110010001101