1
0
mirror of https://github.com/mnaberez/py65.git synced 2024-07-23 11:28:56 +00:00

Merge pull request #36 from scotws/master

Rewrite of itoa() in utils/conversions.py
This commit is contained in:
Mike Naberezny 2017-09-19 09:01:39 -07:00 committed by GitHub
commit c5e01ad788

View File

@ -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):