简体   繁体   English

如何使用位掩码从缓冲区访问六位

[英]How to use bit masking to access six bits from buffer

Let's says I have a buffer and I need to get 6 bits. 假设我有一个缓冲区,我需要获取6位。 Four bits from one element in the buffer and two bits from the next element. 缓冲区中一个元素的四位和下一元素的两位。 I think I know how to access the correct bits from each element but I'm not sure how to combine the bits. 我想我知道如何从每个元素访问正确的位,但是我不确定如何组合位。 Here's some example code. 这是一些示例代码。

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.*/
}

I'm not sure which order you want to combine the bits in, but perhaps you want something like this: 我不确定要组合位的顺序,但是也许您想要这样的东西:

unsigned char lastFourBits = (buffer[i] >> 4) & 0xF;         // 0000xxxx
unsigned char firstTwoBits = (buffer[i+1] & 0x3);            // 000000yy
unsigned char combined = (lastFourBits << 2) | firstTwoBits; // 00xxxxyy

or alternatively: 或者:

unsigned char combined = (firstTwoBits << 4) | lastFourBits; // 00yyxxxx 

The bit shift you are performing here (buffer[i] >> 4) is actually losing the 4 bits that you want. 您在此处执行的移位(buffer[i] >> 4)实际上丢失了您想要的4位。 (buffer[i] & 0xF) will capture the low order four bits of the first byte. (buffer[i] & 0xF)将捕获第一个字节的低四位。 For the second byte, you want the two high order bits (buffer[i+1] & 0xC0) captures those bytes. 对于第二个字节,您希望两个高位(buffer[i+1] & 0xC0)捕获那些字节。

To concatenate: 串联:

value = ((buffer[i] & 0x0F) << 2) + ((buffer[i+1] & 0xC0) >> 6);

An example: If the data stream is 0xABCD, or 1010 1011 1100 1101, this equation captures 101111. 示例:如果数据流是0xABCD或1010 1011 1100 1101,则此等式捕获101111。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM