I have a char*
buffer, that I want to append integers of various bit sizes (between 1
and 32
) to.
Thus, I need a function:
开发者_JAVA百科void addBits(char *buffer, int bits_appended_so_far, int object, int object_bit_size);
that can move an object of, say, 13
bits to the 470
th bit position of buffer.
I could of course shift the bits onto the buffer one by one, but speed is of the essence so it seems like it should be possible to move larger chunks at a time. Is there a standard method to do this? Seems like there should be a standard method, but some googling and SO searching has not given me what I want.
How about something like this:
void addBits(char *buffer, int bits_appended_so_far, int object, int object_bit_size) {
int* int_buffer = reinterpret_cast<int*>(buffer);
const int bits_per_int = 8 * sizeof(int);
int current_int = bits_appended_so_far / bits_per_int;
int current_offset = bits_appended_so_far % bits_per_int;
int_buffer[current_int] |= object << current_offset;
if( current_offset )
int_buffer[current_int+1] |= object >> (bits_per_int - current_offset);
}
This assumes that object
only has the least significant object_bit_size
bits set, otherwise you need to add a step to chop the extra (unwanted) bits off. It also assumes that buffer is initialized to zeros before you start adding the bits.
- Align the bits properly in a 32 bit int using shift.
- Find the location of the byte in the buffer.
- If contents of buffer needs to be preserved, create an int pointer pointing at the relevant byte, then bitwise | the 32-bit int into that location.
- If contents need not be preserved, simply memcpy(buffer location, 32-bit int);
The simplest solution seems to be using a basic memcpy and shifting appropriately if the position is not byte aligned
Standard word sizes are 1,2,4,8 and 16 bytes depend of CPU, so you can shift only 8,16,32,64 or 128 bits at once. There is no standard method!
If you wont to spare with memory space than my proposal is that use as smallest unit one byte instead one bit to avoid bit shifting and speed up function.
EDIT: If memory is priority and bit sizes are between 1 and 32 there is still no problem because most CPUs support more than 1 bit shift at once.
Under x86 you can shif up to 32 bits at once if you are using 32 bit registers.
精彩评论