```
""" 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
```

About the Author

**Are you able to help answer this sponsored question?**

Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.

Recommended Topics