Do you want to find -10 in negaternary? UserPageVisits:201 active 80 80 DaniWeb 561 60 2012-04-27T12:19:31+00:00

Do you want to find -10 in negaternary?


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]

About the Author

IT Pro doing Eng-Fin-Eng translations

code snippet
""" 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
        negative = ''

    # case zero    
    if not n:
        yield '0'
        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

Few first functions to show the values and negate before tackling the generating part for balanced ternary

def balanced_ternary(number_string):
    return val([-1 if c == '-' else (1 if c == '+' else 0) 
                for c in number_string], 3)

def neg(balanced):
    return balanced.replace('-', '*').replace('+', '-').replace('*', '+')

if __name__  == '__main__':
    b = '-0+'
    print('\nBalanced ternary %r value is %i' % (b, balanced_ternary(b)))
    assert balanced_ternary(b) == -balanced_ternary(neg(b))
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.