I have an array of bits (stored as Boolean) that I want to reconstruct into an integer. I want to insert bits from the right hand side and shift them 开发者_StackOverflow社区left for every bit in my array.
How do I insert a bit at the LSB side and shift it over at the same time?
You would do something like this:
bool yourarray[32];
int output = 0;
for(int i = 0; i < 32; i++)
{
// Shift the bits left by 1. The first time through the loop this
// will have no real effect since 0 << 1 == 0.
output <<= 1;
// If this particular bit is "on", activate the LSB using a bitwise-or
if(yourarray[i] == true)
output |= 1; // this turns on the LSB
// We could also do this for completeness, but it has no effect since
// the LSB is already 0:
else
output &= ~1; // this turns off the LSB
}
I'm assuming an int of size 32 here.
There are other considerations to take into account, like endianness but this should give you an idea. Also beware of signing issues, since in this case the highest (left-most) bit will affect whether the int comes out positive or negative.
This is just to give a bit of explanation on what's happening when you use bitwise operators.
Let's say we have a 1 byte (8 bits) value: val1 = 00000011. And we have another 1 byte value: val2 =00100001
If we shift the bits of val1 to the left 2, like so:
val1 = val1 << 2;
val1 now looks like this: 00001100.
Then, if we OR (|) val2 with val1 like this:
val1 = val1 | val2
val1 will look like this: 00101101.
I hope this helps ^_^
精彩评论