如果位缓冲区很长,您的算法就不太好,因为每个输出 trit 都会重复较小的值所需的所有除法n
。因此,将此算法转换为“bignum”算法将不是您想要的。
另一种方法:从左到右扫描位,每个新的都会更新之前的值:
val = val * 2 + bit
带有三元组的三n
进制数t[i]
具有值
sum(i = 0 .. n-1) t[i] * 3^i
因此val
,新扫描位的更新的三元表示变为,
[ 2 * sum(i = 0 .. n-1) t[i] * 3^i ] + bit
= bit + sum(i = 0 .. n-1) 2 * t[i] * 3^i
= 2 * t[0] + b + sum(i = 1 .. n) 2 * t[i] * 3^i
为了使代码简单,让我们计算一个无符号字符数组中的三元组。完成后,您可以以任何您喜欢的方式重新包装它们。
#include <stdio.h>
// Compute the trit representation of the bits in the given
// byte buffer. The highest order byte is bytes[0]. The
// lowest order trit in the output is trits[0]. This is
// not a very efficient algorithm, but it doesn't use any
// division. If the output buffer is too small, high order
// trits are lost.
void to_trits(unsigned char *bytes, int n_bytes,
unsigned char *trits, int n_trits)
{
int i_trit, i_byte, mask;
for (i_trit = 0; i_trit < n_trits; i_trit++)
trits[i_trit] = 0;
// Scan bits left to right.
for (i_byte = 0; i_byte < n_bytes; i_byte++) {
unsigned char byte = bytes[i_byte];
for (mask = 0x80; mask; mask >>= 1) {
// Compute the next bit.
int bit = (byte & mask) != 0;
// Update the trit representation
trits[0] = trits[0] * 2 + bit;
for (i_trit = 1; i_trit < n_trits; i_trit++) {
trits[i_trit] *= 2;
if (trits[i_trit - 1] > 2) {
trits[i_trit - 1] -= 3;
trits[i_trit]++;
}
}
}
}
}
// This test uses 64-bit quantities, but the trit
// converter will work for buffers of any size.
int main(void)
{
int i;
// Make a byte buffer for an easy to recognize value.
#define N_BYTES 7
unsigned char bytes [N_BYTES] =
{ 0xab, 0xcd, 0xef, 0xff, 0xfe, 0xdc, 0xba };
// Make a trit buffer. A 64 bit quantity may need up to 42 trits.
#define N_TRITS 42
unsigned char trits [N_TRITS];
to_trits(bytes, N_BYTES, trits, N_TRITS);
unsigned long long val = 0;
for (i = N_TRITS - 1; i >= 0; i--) {
printf("%d", trits[i]);
val = val * 3 + trits[i];
}
// Should prinet value in original byte buffer.
printf("\n%llx\n", val);
return 0;
}