java - 从 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)
我想将这样的东西用于位压缩编码数据,其中整数可以存储在字节的几位中。
解决方案
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);
}
}
在我尝试过的所有方法中,这是最干净、最简单的方法,但我愿意接受建议!
推荐阅读
- php - 我无法在生日中显示日期格式为 DATE
- javascript - 如何在没有 OAuth2 的情况下获取 youtube-api 频道中的播放列表列表?
- sql-server - 从 Azure BACPAC 还原数据库时出现错误
- java - Arraylist Pang 游戏,箭头类
- amazon-web-services - 如何使用 AWS Fargate 在 Amazon ECS 上启动任务(容器)时为其提供参数
- arrays - 计算特定元素在数组中出现的次数
- mysql - Symfony 4 Doctrine 多个表连接在一个属性中
- laravel - 如果外部 id 作为属性传递,则防止在工厂中创建关系模型
- python - Python 无法从 Kafka 读取 json.loads() 嵌套 JSON
- ios - 如何在 iOS 的 web 视图中更改按钮的背景颜色