首页 > 解决方案 > 从 ByteBuffer 中获取位

问题描述

我正在研究一个 BitBuffer,它将从 ByteBuffer 中获取 x 位作为 int、long 等,但我似乎遇到了很多问题。

我尝试过一次加载很长并使用位移,但困难来自从一个长滚动到下一个。我想知道是否有更好的方法。有人有什么建议吗?

public class BitBuffer 
{
    final private ByteBuffer bb;

    public BitBuffer(byte[] bytes) 
    {       
        this.bb = ByteBuffer.wrap(bytes);
    }

    public int takeInt(int bits) 
    {
        int bytes = toBytes(bits);
        if (bytes > 4) throw new RuntimeException("Too many bits requested");

        int i=0;
        // take bits from bb and fill it into an int
        return i;
    }
}

更具体地说,我试图从缓冲区中获取 x 位并将它们作为 int (最小情况)返回。我可以从缓冲区访问字节,但假设我只想取前 4 位。

例子:

如果我的缓冲区充满“101100001111”,如果我按顺序运行这些:

takeInt(4) // should return 11    (1011)
takeInt(2) // should return 0     (00)
takeInt(2) // should return 0     (00)
takeInt(1) // should return 1     (1)
takeInt(3) // should return 7     (111)

我想将这样的东西用于位压缩编码数据,其中整数可以存储在字节的几位中。

标签: javabit

解决方案


BitSet 和 ByteBuffer 的想法有点难以控制,所以相反,我采用了二进制字符串方法,这基本上让管理中间位缓冲区变得非常头疼。

public class BitBuffer 
{
    final private String bin;
    private int start;

    public BitBuffer(byte[] bytes) 
    {       
        this.bin = toBinaryString(bytes); // TODO: create this function
        this.start = 0;
    }

    public int takeInt(int nbits) 
    {
        // TODO: handle edge cases
        String bits = bin.substring(start, start+=nbits);
        return Integer.parseInt(bits, 2);
    }
}

在我尝试过的所有方法中,这是最干净、最简单的方法,但我愿意接受建议!


推荐阅读