我在 this page on bit twiddling 的帮助下编写了这个函数:
uint16_t *decode(uint64_t instr) {
// decode instr (this is new to me lol)
uint16_t icode = (instr >> 48) & ((1 << 16) - 1);
uint16_t p1 = (instr >> 32) & ((1 << 16) - 1);
uint16_t p2 = (instr >> 16) & ((1 << 16) - 1);
uint16_t p3 = (instr >> 00) & ((1 << 16) - 1);
return (uint16_t[]){icode, p1, p2, p3};
}
我有这个来测试它:
uint16_t *arr = decode(number);
for(int i = 0; i < 4; i++) {
printf("%d\n", arr[i]);
}
但是,无论 number
是什么,这都会打印 0 四次。我还没有解决问题的第一部分,即如何首先对四个 uint16_t 进行编码。
最佳答案
how to encode the four uint16_t's in the first place
这并不难。您所要做的就是加载每个 uint16_t
到 uint64_t
一对一,然后返回 uint64_t
:
uint64_t encode(uint16_t uints[]) {
uint64_t master = 0;
for (uint8_t index = 0; index <= 3; ++index) {
master <<= 16; // Shift master left by 16 bits to create space for the next uint16
master |= uints[index]; // Load uints[index] to the lower 16 bits of master
} // Do this four times
return master;
}
加载uint16_t
s 的顺序相反,只需替换 uint8_t index = 0; index <= 3; ++index
与 uint8_t index = 3; index >= 0; --index
.
关于c - 如何将四个 16 位 uint 编码为 64 位 uint,然后再次解码它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275844/