Here is base conversion function written to deal also with negative bases.
Not yet balanced ternary, where numbers themselves can be negative, maybe later I add it.. Based on the code in the wikipedia article, which has bug for converting 0.[Edit: I fixed the bug in wikipedia]
""" Program to show number in different bases including the negative bases val function for calculating the value of string as number (like extended int) added """ def reversed_negadigits(n, base=-3): """ produce digits of number at base base, also for negative base, in reverse order """ if n < 0 and base > 0: negative = '-' n = -n else: negative = '' # case zero if not n: yield '0' else: while n != 0: n, remainder = divmod(n, base) if remainder < 0: n, remainder = n + 1, remainder - base yield str(remainder) if remainder < 10 else chr(ord('A')+remainder-10) if negative: yield negative def negabase(n, base=-3): return ''.join(reversed(list(reversed_negadigits(n, base)))) def val(number_string, base=-3): return sum(int(n) * base ** p for p, n in enumerate(reversed(number_string))) print('%10s %10s %10s %10s %10s %10s' % ('dec', 'hex', 'bin', 'negabin', 'ternary', 'negaternary')) for t in range(-32,+33): print('%10s %10s %10s %10s %10s %10s' % (t, negabase(t, 16), negabase(t, 2), negabase(t, -2), negabase(t, 3), negabase(t, -3))) assert val(negabase(t)) == t
Be a part of the DaniWeb community
We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.