![](/img/trans.png)
[英]In C, How do I calculate the signed difference between two 48-bit unsigned integers?
[英]How can I create a 48-bit uint for bit mask
我正在尝试创建一个48位整数值。 我知道可以使用char数组或结构,但是我希望能够进行位掩码/操作,但是我不确定该怎么做。
当前该程序使用16位uint,我需要将其更改为48。这是一个字节码解释器,我想将内存地址扩展到4GB。 我可以只使用64位,但这会浪费很多空间。
这是代码示例:
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
}
完整程序: http : //en.wikibooks.org/wiki/Creating_a_Virtual_Machine/Register_VM_in_C
您可以使用位字段,这些位字段通常用于表示已知的固定位宽的整数类型。 位域的一种众所周知的用法是表示一组位和/或一系列位,称为标志。 您可以对其应用位操作。
#include <stdio.h>
#include <stdint.h>
struct uint48 {
uint64_t x:48;
} __attribute__((packed));
将结构或具有特殊功能的uint16_t
数组用于uint48
数组。
对于个别实例,请使用uint64_t
或unsigned long long
。 uint64_t
可以单独用于int48
,但可以屏蔽*
或<<
类的结果操作以清除高位。 数组仅需要一些节省空间的例程。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.