mirror of
https://github.com/mnaberez/py65.git
synced 2024-10-14 04:23:50 +00:00
Merge pull request #36 from scotws/master
Rewrite of itoa() in utils/conversions.py
This commit is contained in:
commit
c5e01ad788
@ -1,20 +1,19 @@
|
|||||||
|
|
||||||
|
|
||||||
def itoa(num, base=10):
|
def itoa(num, base=10):
|
||||||
""" Convert a decimal number to its equivalent in another base.
|
"""Convert a decimal number to its equivalent in base 2 or 16; base 10
|
||||||
This is essentially the inverse of int(num, base).
|
is silently passed through. Other bases raise a ValueError. Returns a
|
||||||
|
string with hex digits lowercase.
|
||||||
"""
|
"""
|
||||||
negative = num < 0
|
if base == 2:
|
||||||
if negative:
|
newnum = "{0:b}".format(num)
|
||||||
num = -num
|
elif base == 16:
|
||||||
digits = []
|
newnum = "{0:x}".format(num)
|
||||||
while num > 0:
|
elif base == 10:
|
||||||
num, last_digit = divmod(num, base)
|
newnum = "{0}".format(num)
|
||||||
digits.append('0123456789abcdefghijklmnopqrstuvwxyz'[last_digit])
|
else:
|
||||||
if negative:
|
msg = 'Could not convert number "{0}" to base "{1}"'.format(num, base)
|
||||||
digits.append('-')
|
raise ValueError(msg)
|
||||||
digits.reverse()
|
|
||||||
return ''.join(digits)
|
return newnum
|
||||||
|
|
||||||
|
|
||||||
def convert_to_bin(bcd):
|
def convert_to_bin(bcd):
|
||||||
|
Loading…
Reference in New Issue
Block a user