c - 如何将四个 16 位 uint 编码为 64 位 uint,然后再次解码它们?

标签 c bit-manipulation

我在 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_tuint64_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; ++indexuint8_t index = 3; index >= 0; --index .

关于c - 如何将四个 16 位 uint 编码为 64 位 uint,然后再次解码它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275844/

相关文章:

c - 如何理解宏定义不变

java - Java 中签署扩展任意长度位模式的最有效方法是什么?

algorithm - 通过位操作处理负数

c++ - 获取 'ones' 数字在 C float 的 base-2 表示中的位置

c - 对文件进行快速排序

c - 在 C 中实现 ceil()

c - Pthread程序死锁使用条件变量

在内存中将 BMP 文件转换为 PNG 文件

c - 位破解 : Expanding bits

c++ - 修改 WAH 压缩位图性能