Java: reading a variable number of bits and converting to an integer

China☆狼群 提交于 2019-12-11 09:04:14

问题


I need to write a method which reads a variable number of bits from a ByteBuffer and converts those bytes into a primitive int or long (if more than 32 bits). I am not very proficient at working with bits, but I did look at some code examples and answers to similar(ish) questions and here is the best that I could come up with (bb refers to an internal ByteBuffer):

    public int readBits(int number) {
        int initialPosition = bb.position();
        int value = 0;
        int remaining = number;
        int position = bb.position();
        while (remaining > 0) {
            int index = (position >> 3);
            int bit = (position & 7);
            int bitsLeft = Math.min(8 - bit, remaining);
            int nibble = (bb.get(index) >> (bit & BIT_MASKS[bitsLeft]));
            value |= nibble << (number - remaining);
            position += bitsLeft;
            remaining -= bitsLeft;
        }
        bb.position(initialPosition + ((position - initialPosition) >> 3));
        return value;
    }

The BIT_MASKS array is defined as following:

    private static final int[] BIT_MASKS = new int[] { 0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff };

I tested this method using this test code:

public static void main(String[] args) {
    int nm = 4;
    BitSet bs = new BitSet(nm);
    bs.set(2);
    bs.set(3);
    BitBuffer bb = new BitBuffer(ByteBuffer.wrap(bs.toByteArray()));
    System.out.println(bb.readBits(nm));
}

I expected a value of 6, but it prints 12 and I'm not sure why.

I would appreciate some help with this. Thanks.

来源:https://stackoverflow.com/questions/23530554/java-reading-a-variable-number-of-bits-and-converting-to-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!