将压缩半字节扩展为 5 位组

Expanding packed nibbles to 5-bit groups

我目前有一个 64 位的无符号整数,其中包含:

0100
0100
0100
0100
0000...

我会把它改成:

01000
01000
01000
01000
00000...

有办法吗?

谢谢

省略前导 0,它没有任何作用 => 左移一位

📎你好!看起来您正在尝试将 4 位半字节扩展为 5 位组。

一般情况下,你可以这样做

uint64_t value = YOUR_DATA;  //this has your bits.
for (int i; i< sizeof(value)*2; i++) {
   uint8_t nibble = (value & 0xF);
   nibble <<= 1; //shift left 1 bit, add 0 to end.
   STORE(nibble, i);
   value>>=4;  //advance to next nibble         
}

这将为每组 4 位调用一次 STORE。 STORE 的参数是 "expanded" 5 位值和半字节计数器,其中 0 表示最低有效 4 位。

要回答的设计问题是如何存储结果? 64 位 / 4 * 5 = 80 位,所以你要么需要 2 个字,要么在一端丢弃数据。

假设 2 个词的锚点位于 LSB,STORE 可能看起来像

 static uint64_t result[2] = {0,0};
 void STORE(uint64_t result[], uint8_t value, int n) {
    int idx = (n>12);                //which result word?
    result[idx] |= value << ( n*5 - idx*64 );
    if (n==12) result[1] |= value>>4; //65th bit goes into 2nd result word
 }