In order to parse a binary stream of unmanaged data, I have to recreate data types. The data is compressed which means I read 2 bytes which actually represent a 6-bit byte value and a 10-bit short value.
All I need to do is copy a bit-sequence from one value to another. I know the start bit and length for the source value and the destination value. So far I have made two approaches which both copy the right bits but somehow in reverse order.
byte BitwiseCopy(short value, int sourceStartBit, int destStartBit, int bitCount)
{
short result = 0;
for (int i = 0; i < bitCount; i++)
//result |= (byte) (value & (1 << sourceStartBit + i) | (result & (1 << (destStartBit + bitCount) - i)));
result |= (short) (value & (1 << sourceStartBit + i));
return (byte) (result >> ((destStartBit - bitCount) + sizeof(byte) * 8));
}
For my test scenario I am using a short with the following value:
0000 0000 1101 0011
^15 ^0
My goal is to copy the 4-th - 7-th bit of this short to a byte's 0-3rd bits.
When I use either the commented line (without the code in the return clause) approach or the way it's currently highlighted, I always get this result:
0000 1011
^7 ^0
So what I want, just reversed. I'm sure it's something tiny, but what am I overlooking here? I don't get why it reverses order. The bit-shifting approach (copying directly bitwise and shifting it to the correct position) shouldn't reverse it, should it?
EDIT:
The method always has an input of type short. I have 3 parameters: sourceStart which is the bit I start to copy from the input value (low to high), destStart which is the bit I copy to into my destination (which is either byte or short - I would make two specific methods for this) and bitCount which is the amount of bits (starting from low to high order) I want to copy.
The method must copy bits in correct order. So for example CopyBitwise(input, 4, 0, 4) should return (left: high, right: low order) 0000 1011 given this input:
input [short]: ... 1011 0110
^8th ^0th
Another one:
input [short]: 1011 0110 0100 0111
^15th ^0th
^end ^start
CopyBitwise(input, 7, 3, 5) should result in
0011 0000
^8th ^0th
^end ^start
shortor abyte[2]is not the same). - bommelding