简体   繁体   中英

How to replace/overwrite an arbitrary number of bits in an arbitrary position in an array of short with arbitrary bits from an integer

I have a function I'm trying to write of the following form (and haven't found exactly what I'm looking for — if this is a dup please just point me at the right place — even if it's not int s and short s but, say, char s and int s instead, that would be fine):

put_bits(short *array_of_short, int significant_bits, int bit_offset, int integer_to_append)

Where I overwrite the the significant_bits of integer_to_append at bit_offset in array_of_short .

I'd like to accomplish things by just overwriting (or bitwise oring, or overlaying, or replacing) bits to the position in the array (I don't want to add more elements to the array or allocate more memory) — ie it should be easily possible, but pretty inefficient, to just keep track of how many elements into the array the offset translates to, whether this falls on a boundary of the shorts and shift the bits of the integer to the appropriate offset and or them onto the appropriate short(s) — but that seems like loads of overhead and calculating more than I need to vs just oring the bits into the appropriate spot, but I'm kind of at a loss...

So, for example, I have an integer which will contain an arbitrary number of "significant" bits — let's say for this example there are 6. So the values would be from 0 to 63

0000 0000 0000 0000 0000 0000 0000 0000

to

0000 0000 0000 0000 0000 0000 0011 1111

and I want to overlay (or bitwise or this) this to an arbitrarily sized array of short at an arbitrary point. So if I had

Integer:

0000 0000 0000 0000 0000 0000 0010 0001

Array of short:

0100 1000 0100 1100 : 1100 0010 0110 0000 : 0000 0000 0000 0000 : 0000 0000 0000 0000

and I wanted to append at position 42 to get:

0100 1000 0100 1100 : 1100 0010 0110 0000 : 0000 0000 0000 1000 : 0100 0000 0000 0000

If I'm totally off or I don't make sense, let me know too.

If i understand your question correctly, you actually want to treat your array as array of bits. There is no such structure in c as bit array of course, but you can implement it. Here is example of bit array with int as base type. You can adopt this solution with short as base type, and then just set bit by bit something like that:

for( i = 0 ; i< sizeof(int)*8;++i)
{
       unsigned int flag = 1;
       flag = flag << i;
       if( int_num & flag)
           SetBit( array_of_short, bit_offset + i ); 
}

void  SetBit( short array_of_short[ ],  int k )
{
   array_of_short[k/16] |= 1 << (k%16);  // Set the bit at the k-th position in  array_of_short[i]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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