[英]How do I parse out n-bit elements from a byte addressable array
我有一個只能以8位字節尋址的數據流,我想把它解析成6位元素並將其存儲到數組中。 有沒有最知名的方法來做到這一點?
11110000 10101010 11001100
成
像一個數組
111100|001010|101011|001100
(可以零填充,只需要通過這種方式尋址)
數據是一個8位數組,也是6位的倍數,不是真的無窮無盡
取決於一個字節在您的特定體系結構上有多少位。 在六位架構上它很簡單:-)
假設每字節8位架構,您將不得不做一些事情:
int sixbits(unsigned char* datastream, unsigned int n) {
int bitpos = n*6;
return (datastream[bitpos/8] >> bitpos%8) // lower part of the five bit group
+ (datastream[bitpos/8+1] << 8-bitpos%8) // if bitpos%8>2, we need to add some carry bits from the next char
& 0x3f; // and finally mask the lowest 6 bits
}
其中n是第n個6位組。 任何體面的編譯器都會用移位替換除法,用ands替換模數。 只需在循環中使用此函數即可填充目標數組。
您計算5位序列,讀取每個字節,根據計數器和預期的字位置(通過從相鄰字節字中xor-ing片段)移位位,然后形成新的正確對齊的字節字,然后處理。
我希望你不要指望代碼......
你可以使用bit fiddling來做到這一點:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
unsigned char source[3] = { 15, 85, 51 };
unsigned char destination[4];
memset(destination, 0, 4);
for (int i = 0; i < (8 * 3); ++i)
{
destination[i / 6] |= ((source[i / 8] >> (i % 8) & 1) << (i % 6));
}
for (int j = 0; j < 4; ++j)
printf("%d ", destination[j]);
}
輸出:
15 20 53 12
請注意,這從五個最低有效位開始工作。
15 85 51
11110000 10101010 11001100
111100 001010 101011 001100
15 20 53 12
要首先獲得最重要的信息,請執行以下操作:
destination[i / 6] |= ((source[i / 8] >> (7 - (i % 8))) & 1) << (5 - (i % 6));
假設您首先編寫了最重要的位,這就像您的示例一樣:
240 170 204
11110000 10101010 11001100
111100 001010 101011 001100
60 10 43 12
如何使用這樣的結構:
struct bit5
{
unsigned int v1 : 5;
unsigned int v2 : 5;
unsigned int v3 : 5;
unsigned int v4 : 5;
unsigned int v5 : 5;
unsigned int v6 : 5;
unsigned int v7 : 5;
unsigned int v8 : 5;
};
然后每8個字節(40位= 8個5位組,適合8個字節)將您的字節數組轉換為struct bit5
,以獲得5位塊。 說:
unsigned char* array; // a byte array that you want to convert
int i;
struct bit5* pBit5;
for(i = 0; i < (int)(SIZE_OF_ARRAY / 8); i++)
pBit5 = (struct bit5*)((int)array + i * 8);
我會考慮使用BitStream。 它允許您一次讀取一位。 您可以將該位直接移位(使用<< n)。 它可能無法一次讀取8位字節,但它肯定會是更清晰的代碼。
這個聯盟怎么樣?
union _EIGHT_TO_SIX_ {
struct {
unsigned char by6Bit0 : 6;
unsigned char by6Bit1 : 6;
unsigned char by6Bit2 : 6;
unsigned char by6Bit3 : 6;
} x6;
struct {
unsigned char by8Bit0;
unsigned char by8Bit0;
unsigned char by8Bit0;
} x8;
}
設置by8Bitx將自動填入6Bitx ~~~
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.