Non-decimal radices/Convert: Difference between revisions

→‎{{header|Python}}: Reformat. Don't concatenate strings in a loop.
(→‎{{header|Python}}: Reformat. Don't concatenate strings in a loop.)
Line 2,524:
 
=={{header|Python}}==
Converting from===Python: string to number is easy:===
Converting from string to number is straight forward:
<lang python>i = int('1a',16) # returns the integer 26</lang>
 
===Python: number to string===
Converting from number to string is harder:
;Recursive:
 
<lang python>digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
return (((num == 0) and "0" )
or ( baseN(num // b, b).lstrip("0")
+ digits[num % b]))</lang>
 
;Iterative:
# alternatively:
 
def baseN(num,b):
<lang>digits = [[ch] for ch in "0123456789abcdefghijklmnopqrstuvwxyz"]
if num == 0: return "0"
 
result = ""
def while baseN(num, != 0b):
if num, d == divmod(num, b)0:
result += digits[d] return "0"
return result[::-1] #= reverse[]
while num != 0:
num, d = divmod(num, b)
result += ""digits[d]
return ''.join(result[::-1])</lang>
 
;Sample run from either:
 
<pre>In [1: baseN(26, 16)
k = 26
Out[1]: '1a'</pre>
s = baseN(k,16) # returns the string 1a</lang>
 
=={{header|R}}==
Anonymous user