Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Reformat. Don't concatenate strings in a loop.)
Line 2,524: Line 2,524:


=={{header|Python}}==
=={{header|Python}}==
Converting from string to number is easy:
===Python: string to number===
Converting from string to number is straight forward:
<lang python>i = int('1a',16) # returns the integer 26</lang>
<lang python>i = int('1a',16) # returns the integer 26</lang>

===Python: number to string===
Converting from number to string is harder:
Converting from number to string is harder:
;Recursive:

<lang python>digits = "0123456789abcdefghijklmnopqrstuvwxyz"
<lang python>digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
def baseN(num,b):
return (((num == 0) and "0" )
return (((num == 0) and "0" )
or ( baseN(num // b, b).lstrip("0")
or ( baseN(num // b, b).lstrip("0")
+ digits[num % b]))
+ digits[num % b]))</lang>


;Iterative:
# alternatively:

def baseN(num,b):
<lang>digits = [[ch] for ch in "0123456789abcdefghijklmnopqrstuvwxyz"]
if num == 0: return "0"

result = ""
while num != 0:
def baseN(num, b):
num, d = divmod(num, b)
if num == 0:
result += digits[d]
return "0"
return result[::-1] # reverse
result = []
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}}==
=={{header|R}}==