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

戏子无情 提交于 2019-12-06 15:16:05

问题


I am trying to create a 48-bit integer value. I understand it may be possible to use a char array or struct, but I want to be able to do bit masking/manipulation and I'm not sure how that can be done.

Currently the program uses a 16-bit uint and I need to change it to 48. It is a bytecode interpreter and I want to expand the memory addressing to 4GB. I could just use 64-bit, but that would waste a lot of space.

Here is a sample of the code:

unsigned int program[] = { 0x1064, 0x11C8, 0x2201, 0x0000 };

void decode( )
{
  instrNum = (program[i] & 0xF000) >> 12; //the instruction
  reg1     = (program[i] & 0xF00 ) >>  8; //registers
  reg2     = (program[i] & 0xF0  ) >>  4;
  reg3     = (program[i] & 0xF   );
  imm      = (program[i] & 0xFF  ); //pointer to data
}

full program: http://en.wikibooks.org/wiki/Creating_a_Virtual_Machine/Register_VM_in_C


回答1:


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));



回答2:


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);
}


来源:https://stackoverflow.com/questions/26197928/how-can-i-create-a-48-bit-uint-for-bit-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!