How can I create a 48-bit uint for bit mask

早过忘川 提交于 2019-12-04 20:50:23

You can use the bit fields which are often used to represent integral types of known, fixed bit-width. A well-known usage of bit-fields is to represent a set of bits, and/or series of bits, known as flags. You can apply bit operations on them.

#include <stdio.h>
#include <stdint.h>

struct uint48 {
    uint64_t x:48;
} __attribute__((packed));

Use a structure or uint16_t array with special functions for an array of uint48.

For individual instances, use uint64_t or unsigned long long. uint64_t will work fine for individually int48, but may want to mask off the results operations like * or << to keep upper bits cleared. Just some space saving routines are needed for arrays.

typedef uint64_t uint48;
const uint48 uint48mask = 0xFFFFFFFFFFFFFFFFull; 

uint48 uint48_get(const uint48 *a48, size_t index) {
  const uint16_t *a16 = (const uint16_t *) a48;
  index *= 3;
  return a16[index] | (uint32_t) a16[index + 1] << 16
          | (uint64_t) a16[index + 2] << 32;
}

void uint48_set(uint48 *a48, size_t index, uint48 value) {
  uint16_t *a16 = (uint16_t *) a48;
  index *= 3;
  a16[index] = (uint16_t) value;
  a16[++index] = (uint16_t) (value >> 16);
  a16[++index] = (uint16_t) (value >> 32);
}

uint48 *uint48_new(size_t n) {
  size_t size = n * 3 * sizeof(uint16_t);
  // Insure size allocated is a multiple of `sizeof(uint64_t)`
  // Not fully certain this is needed - but doesn't hurt.
  if (size % sizeof(uint64_t)) {
    size += sizeof(uint64_t) - size % sizeof(uint64_t);
  }
  return malloc(size);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!