1

Part of my application data contains a set of 9 ternary (base-3) "bits". To keep the data compact for the database, I would like to store that data as a single short. Since 3^9 < 2^15 I can represent any possible 9 digit base-3 number as a short.

My current method is to work with it as a string of length 9. I can read or set any digit by index, and it is nice and easy. To convert it to a short though, I am currently converting to base 10 by hand (using a shift-add loop) and then using Int16.Parse to convert it back to a binary short. To convert a stored value back to the base 3 string, I run the process in reverse. All of this takes time, and I would like to optimize it if at all possible.

What I would like to do is always store the value as a short, and read and set ternary bits in place. Ideally, I would have functions to get and set individual digits from the binary in place.

I have tried playing with some bit shifts and mod functions, but havn't quite come up with the right way to do this. I'm not even sure if it is even possible without going through the full conversion.

Can anyone give me any bitwise arithmetic magic that can help out with this?

captncraig
  • 22,118
  • 17
  • 108
  • 151

3 Answers3

1
public class Base3Handler
{
    private static int[] idx = {1, 3, 9, 27, 81, 243, 729, 729*3, 729*9, 729*81};

    public static byte ReadBase3Bit(short n, byte position)
    {
        if ((position > 8) || (position < 0))
            throw new Exception("Out of range...");
        return (byte)((n%idx[position + 1])/idx[position]);
    }

    public static short WriteBase3Bit(short n, byte position, byte newBit)
    {
        byte oldBit = ReadBase3Bit(n, position);
        return (short) (n + (newBit - oldBit)*idx[position]);
    }
}
Farshid Zaker
  • 1,960
  • 2
  • 22
  • 39
0

These are small numbers. Store them as you wish, efficiently in memory, but then use a table lookup to convert from one form to another as needed.

-1

You can't do bit operations on ternary values. You need to use multiply, divide and modulo to extract and combine values.

To use bit operations you need to limit the packing to 8 ternaries per short (i.e. 2 bits each)

adrianm
  • 14,468
  • 5
  • 55
  • 102