gpt4 book ai didi

c++ - 3 位元素对数组

转载 作者:搜寻专家 更新时间:2023-10-31 00:49:37 25 4
gpt4 key购买 nike

由于内存限制,我必须将一些值对存储在一个 6 位/对(3 位/值)的数组中。当我想根据对的索引像普通数组一样访问这个数组时,问题就来了。数组看起来像这样

|--byte 0 | --byte 1 | --byte 2  
|00000011 | 11112222 | 22333333 ... and so on, the pattern repeats.
|------|-------|--------|------|
pair 0 pair 1 pair 2 pair 3

=> 4 pairs / 3 bytes

您可以看到有时(对于可被 1 和 2 整除的索引)需要 2 个字节来提取值。
我创建了一个给定索引的函数,返回该对中的第一个值(3 位)和另一个值(也是 3 位)。

void GetPair(char *array, int index, int &value1, int &value2) {
int groupIndex = index >> 2; // Divide by 4 to get the index of the group of 3 bytes (with 4 pairs)
// We use 16 bits starting with the first byte from the group for indexes divisible by 0 and 1,
// 16 bits starting with the second byte when divisible by 2 and 3
short int value = *(short int *)(array + groupIndex + ((index & 0x02) >> 1));

switch(index & 0x03) { // index % 4
case 0: {
// extract first 3 bits
value1 = (value & 0xE000) >> 13;
// extract the next 3 bits
value2 = (value & 0x1C00) >> 10;
break;
}
case 1: {
value1 = (value & 0x380) >> 7;
value2 = (value & 0x70) >> 4;
break;
}
case 2: {
value1 = (value & 0xE00) >> 9;
value2 = (value & 0x1C0) >> 6;
break;
}
case 3: {
value1 = (value & 0x38) >> 2;
value2 = value & 0x7;
break;
}
}

现在我的问题是:有没有更快的方法来提取这些值?

我做了一个测试,当使用 2 个字节/对(1 个字节/值)时,大约需要 6 秒才能访问所有对(总共 53 个)1 亿次。使用紧凑数组时,大约需要 22 秒 :((可能是因为它需要计算所有这些掩码和位移)。
我尽量解释清楚了...如果不明白请原谅我。

最佳答案

这个怎么样?它消除了对掩码和移位值的内存访问。 (当然,(不可移植的)假设是 char 是 8 位,short 是 16 位。还假设 index * 6 不会溢出 int。)

void GetPair(char *array, int index, int &value1, int &value2)
{
unsigned shift = 10 - index * 6 % 8;
unsigned short data = (*(unsigned short *)(array + index * 6 / 8) >> shift) & 0x3f;
value2 = data & 7;
value1 = data >> 3;
}

不过,读取超过 16 位边界的短数据可能会受到惩罚。当我还在跟踪这些事情的时候,曾经有过这样的问题。如果是这种情况,从 16 位边界开始读取 32 位值并相应地调整移位和掩码可能会更好。

关于c++ - 3 位元素对数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1053242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com