I need to convert arbitary length binary into an exact ternary representation. Ideally, given an array of bits char buffer[n], the algorithm would be able to produce a array of trits(analog of bits), and vice versa. Is there such an algorithm?
I am aware of ways to convert individual int to ternary:
int nth_trit(int num, int n)
{
for(int i = 0; i < n; i++)
num /= 3;
return num % 3;
}
Alas, with a bitstream even a long long long int wouldn’t suffice. I think using a big integer library would suffice, although I’m not sure, and feel that there should be better way calculate the ternary representation.
A visual example:
// Conversion is simple(short stream)
Binary - 0 1 0 0 1 0 0 1
Decimal - 7 3
Ternary - 2 2 0 1
// Conversion is hard(long stream)
Binary - 1 0 1 0 0 0 0 1 ..........
Ternary - ? ? ?
The short stream is simple because, since it nicely fits into an int, the nth_trit function can be used, but the long stream doesn’t, and so apart from using a big integer library, no easy solution occurs to me.
Your algorithm is not so good if the bit buffer is long because each output trit repeats all the divisions also needed for smaller values of
n. So converting this algorithm to “bignum” arithmetic will not be what you want.Another approach: scanning the bits left to right, each new one updates the previous value:
A trinary number with
ntritst[i]has the valueSo a trinary representation of
valupdated for a new scanned bit becomes,To make the code simple let’s compute the trits in an array of unsigned chars. After they’re done you can repack them any way you like.