📄 getbits.c
字号:
/* Get bits from central repository of data. Enter with starting pointer into source, a destination pointer, the endianness and number of bits to get. Returns with new starting pointer and bits shifted to lsb of correct offset depending on endianness. do bounds checking externally.*/#include "randtest.h"void getbits( SRCPTR *src, unsigned char *dst, int endian, int numbits){ unsigned long bitstore; int mscount, bp, shift, mask, sp; /* figure out how many bytes to deal with */ if(numbits & 7) mscount = numbits/8; else mscount = (numbits-1)/8; /* copy data to destination. For big endian, work lsb to msb by going from high offset to low. For little endian, lsb to msb goes from low offset to high.*/ if (endian) { bp = mscount; // start at end sp = (numbits + 7 - src->bitpos)/8; // end pointer in source if (! (numbits & 7)) sp--; // adjust for perfect boundary shift = (src->bitpos - numbits + 1) % 8; // find last bit, +1 for shift amount if ( shift < 0) shift += 8; while( bp >= 0) { if( !shift) dst[bp] = (src->byteptr)[sp]; else { // combine two bytes in big endian order bitstore = (src->byteptr)[sp-1] << 8 | (src->byteptr)[sp]; dst[bp] = (bitstore >> shift) & 0xff; // and keep correct 8 of them } bp--; sp--; } if( (numbits & 7) ) { mask = 0xff >> 8 - (numbits %8); // then clear out dst[0] &= mask; // unused msb's }/* bits copied, now update source pointer */ src->byteptr += (numbits + 7 - src->bitpos)/8; src->bitpos = (src->bitpos - numbits) % 8; if( src->bitpos < 0) src->bitpos += 8; } else // little endian { shift = src-> bitpos; for( bp = 0; bp <= mscount; bp++) { if( !shift) dst[bp] = (src->byteptr)[bp]; else { // get two bytes in little endian order bitstore = (src->byteptr)[bp+1] << 8 | (src->byteptr)[bp]; dst[bp] = (bitstore >> shift) & 0xff; }// printf("dst[%d]=%x\n", bp, dst[bp]); } mask = (8 - numbits) % 8; // actually (src->bitpos + d - shift)%8, but terms cancel if (mask < 0) mask += 8; if( mask) dst[mscount] &= (0xff >> mask);/* bits copied, now update source pointer */ src->byteptr += (numbits + src->bitpos)/8; src->bitpos = (src->bitpos + numbits) % 8; } //printf("new pointer = %x, offset = %d\n", src->byteptr, src->bitpos); } // end of getbits
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -