Anonymous user
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 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:
<lang>digits = [[ch] for ch in "0123456789abcdefghijklmnopqrstuvwxyz"]
result = ""▼
def
if num
while num != 0:
num, d = divmod(num, b)
return ''.join(result[::-1])</lang>
;Sample run from either:
<pre>In [1: baseN(26, 16)
Out[1]: '1a'</pre>
=={{header|R}}==
|