سؤال

I need to read a byte from a .bin but starting from the specific bit, for example:

If I have this two bytes:

01010111 10101100

The program should be able to read from any bit, let's say starting in bit number 3 (or index 2):

01[010111 10]101100

And the result should be 01011110

I can read a byte starting from any bit except when the starting bit is the one at the end of a byte: 0101011[1 ...] //returns something different..

my code is:

byte readByte(int indexInBits, byte[] bytes)
    {
        int actualByte = (indexInBits+1)/8;
        int indexInByte = (indexInBits)%8;
        int b1 = bytes[actualByte] << indexInByte;
        int b2 = bytes[actualByte+1] >> 8 - indexInByte;
        return (byte)(b1 + b2);
    }

What is wrong with it?

Thanks

هل كانت مفيدة؟

المحلول

byte ReadByte(int index, byte[] bytes)
{
    int bytePos = index / 8;
    int bitPos = index % 8;
    int byte1 = bytes[bytePos] << bitPos;
    int byte2 = bytes[bytePos + 1] >> 8 - bitPos;
    return (byte)(byte1 + byte2);
}

I couldn't verify this right now, but this should work as expected.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top