C: 访问字符数组中连续的12位序列



我想对存储在char数组中的measurement执行Golay编码/解码。因此,我需要访问测量的连续12位,这些测量被传递到编码器/解码器。

char数组是22字节长的,看起来像这样,例如:

unsigned char measurement1[22] =
{0xb5, 0x31, 0xc6, 0x51, 0x84, 0x26, 0x2c, 0x69, 0xfd, 0x9e,
0xef, 0xd4, 0xcf, 0xf1, 0x24, 0xd4, 0xf1, 0x97, 0xe5, 0x81, 
0x02, 0xf8}

目前,我正在将char数组转换为相应位的数组,并将其传递给编码器。然而,这种方法非常消耗内存,因为位数组也是一个字符数组,0或1,总共有176个字节(22*8)。

是否有一种更节省内存的方法,它不依赖于将字节数组转换为一系列位,而是访问连续的12位并将其传递给解码器?

谨致问候,P.

将索引i不是转换为基于1字节的偏移量到8位,而是转换为基于12位的偏移量。然后这取决于你是在索引偶数还是奇数的12位三元组:

for (i=0; i<22*8/12; i++)
{
    printf ("%03x ", (i & 1) ? measurement1[3*i/2+1]+((measurement1[3*i/2] & 0x0f)<<8) : (measurement1[3*i/2]<<4)+((measurement1[3*i/2+1]>>4) & 0x0f) );
}

这假设您的测量阵列是从左到右读取的,即

0xb5, 0x31, 0xc6

转换为

0xb53 0x1c6

如果您的订单不同,您需要调整位偏移。

包含12位的倍数是否重要?

未经测试,我相信你可以进一步简化它。。。

int i = 0, left = 8, v = 0;
do
{
  v = 0;
  switch (left)
  {
     case 8:
     {
        v = measurement1[i++];
        v = (v << 4) | (measurement1[i] >> 4); // please handle end here correctly
        left = 4;
        break;
     }
     case 4:
     {
       v = measurement1[i++] & 0x0F; // lower nibble
       v = (v << 8) | measurement1[i++];  // please handle end here correctly
       left = 8;
       break;
     }
  }
  // Now encode v
} while (i < 22);

您可以将mesurement"解析"为12位数组:

typedef union { // you can use union or struct here
    uint16_t i : 12;
} __attribute__((packed)) uint12_t;
printf("%u", ((uint12_t*) mesurement)[0]);

这将打印数组的前12位。

最新更新