News for hackers. Stuff that matters.
Re:How to save multiple numbers into one byte by smaddox on Friday December 02, 2016 @09:48PM (#13093988)
And if you need to store values that are not powers of 2, you can use the following kind of encoding/decoding. In python3:

    from math import *

    def number_to_trits(n):
        # little-endian encoding
        # (i.e. smallest precision trit first)
        trits = []
        v = n
        for i in range(1,9):
            v, d = divmod(v, 3**i)
            trits.append(d)
        return trits

    print(number_to_trits(8))
    # [2, 2, 0, 0, 0, 0, 0, 0]

    def trits_to_number(trits):
        n = 0
        for i, trit in enumerate(trits):
            n += trit*3**i
        return n

    print(trits_to_number([2,2]))
    # 8

There are no comments on this comment yet.