标签:type bit rem printf end void its char 音频
在音频流解析过程中,常常会涉及到顺序读取某些bit的操作。
#include<stdio.h>
typedef struct _BIT_BUF {
unsigned char buffer[1024];
unsigned int byteSize;
unsigned int bytePosition;
unsigned int bitPosition;
unsigned int wBytePosition;
}tBitBuffer;
unsigned int mask(unsigned int bit){
switch (bit) {
case 1:
return 0x1;
break;
case 2:
return 0x3;
break;
case 3:
return 0x7;
break;
case 4:
return 0xf;
break;
case 5:
return 0x1f;
break;
case 6:
return 0x3f;
break;
case 7:
return 0x7f;
break;
case 8:
return 0xff;
break;
}
}
unsigned long bitBuffer_readBits(tBitBuffer *pBitBuffer, unsigned int bits) {
unsigned long result = 0;
if (bits > 64) {
return 0;
}
if (pBitBuffer->bytePosition + (pBitBuffer->bitPosition + bits + 7)/8 >pBitBuffer->byteSize) {
return 0;
}
unsigned int bitsRemainning = 8 - pBitBuffer->bitPosition;
while (bits != 0) {
printf("bits:%d,bitPositon:%d, bitsRemainning:%d\n", bits, pBitBuffer->bitPosition, bitsRemainning);
if (bitsRemainning > bits) {
result <<= bits;
pBitBuffer->bitPosition += bits;
bitsRemainning -= bits;
result |= (pBitBuffer->buffer[pBitBuffer->bytePosition] >> bitsRemainning) & mask(bits);
printf("result:0x%x\n",result);
bits = 0;
}
else {
result <<= bitsRemainning;
result |= pBitBuffer->buffer[pBitBuffer->bytePosition] & mask(bitsRemainning);
printf("result:0x%x\n",result);
bits -= bitsRemainning;
pBitBuffer->bitPosition += bitsRemainning;
}
if (pBitBuffer->bitPosition == 8) {
pBitBuffer->bitPosition = 0;
bitsRemainning = 8;
pBitBuffer->bytePosition++;
}
}
return result;
}
int bitBuffer_addByte(tBitBuffer *pBitBuffer, unsigned char byte){
pBitBuffer->buffer[pBitBuffer->wBytePosition ++] = byte;
pBitBuffer->byteSize ++;
}
void main(void) {
tBitBuffer bitBuffer;
bitBuffer.byteSize = 0;
bitBuffer.bytePosition = 0;
bitBuffer.bitPosition = 0;
bitBuffer.wBytePosition = 0;
bitBuffer_addByte(&bitBuffer, 0x56);
bitBuffer_addByte(&bitBuffer, 0xe2);
unsigned long result = 0;
result = bitBuffer_readBits(&bitBuffer, 2/*11*/);
printf("result:0x%x, %d, bitPostion:%d, bytePosition:%d,byteSize:%d, wBytePosition:%d\n", result,result, bitBuffer.bitPosition, bitBuffer.bytePosition, bitBuffer.byteSize, bitBuffer.wBytePosition);
#if 0
result = bitBuffer_readBits(&bitBuffer, 3);
printf("result:0x%x, %d, bitPostion:%d, bytePosition:%d,byteSize:%d, wBytePosition:%d\n", result,result, bitBuffer.bitPosition, bitBuffer.bytePosition, bitBuffer.byteSize, bitBuffer.wBytePosition);
result = bitBuffer_readBits(&bitBuffer, 6);
printf("result:0x%x, %d, bitPostion:%d, bytePosition:%d,byteSize:%d, wBytePosition:%d\n", result,result, bitBuffer.bitPosition, bitBuffer.bytePosition, bitBuffer.byteSize, bitBuffer.wBytePosition);
#endif
}
标签:type bit rem printf end void its char 音频
原文地址:http://www.cnblogs.com/fellow1988/p/7407198.html