讓我們說我有一個緩衝區,我需要得到6位。緩衝區中一個元素的四位和下一個元素的兩位。我想我知道如何從每個元素訪問正確的位,但我不知道如何組合這些位。這是一些示例代碼。如何使用位掩碼從緩衝區訪問6位
FILE * pFile;
long lSize;
unsigned char * buffer;
//int16_t * buffer;
size_t result;
pFile = fopen ("TestFile.jpg" , "rb");
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
//lSize = (ftell (pFile))/2;
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (unsigned char*) malloc (sizeof(unsigned char)*lSize);
//buffer = (int16_t*) malloc (sizeof(int16_t)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
//result = fread (buffer,2,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// I think this should get the last four bits of this element (buffer[i] >> 4) & 0xF)
// I think this should get the first two bits from the next element (buffer[i+1] & 0x3)
if (32 == (((buffer[i] >> 4) & 0xF) & (buffer[i+1] & 0x3))){
/*Do something.*/
}
4位,你從第一個字節需要哪些,你需要從第二位開始哪兩位?在那之後,如果他們需要連接起來,他們應該在什麼順序? –
感謝您的回覆。在這個例子中,第一個字節中的最後四個和第二個中的前兩個。然後爲了連接,第一個字節首先出現。所以我從緩衝區中獲得了六次連續咬傷。 – Kahless
因此,對於位數爲「abcdefgh ijklmnop」的兩個字節,您需要一個包含「00efghij」位的單個字節?那是對的嗎? – Makyen