自己写的bit工具

最近因项目需要,要把数据以最紧凑的方式存放,因此需要精确到bit,网上好像找不到现成的工具,只好自己写了一个BitBuffer,类似ByteBuffer的处理,当然现在还只是最基本的功能,不过总比没有好。

现在托管在github上:

https://github.com/xiaosunzhu/bit_utils

简单用法:

byte[] data = { (byte)210, 50 }; // 11010010  00110010
BitBuffer buffer = BitBuffer.wrapBytes(data);

System.out.println(buffer.remainingBits()); // 16

byte bit = buffer.getByte(2); // get 2 bits, return in a byte.
// This bit is 3.

System.out.println(buffer.remainingBits()); // 14

bit = buffer.getByte(7,8); // This means get 8 bits from 7 position, return in a bytes.
// This bit is 25(00011001).

System.out.println(buffer.remainingBits()); // 14, not change.

// or  byte[] bits = buffer.getBytes(12); // This means get 12 bits, return in 2 bytes.
// This bits is {210, 3}
byte data = (byte)9; // 1001
BitBuffer buffer = BitBuffer.allocate(20);
buffer.put(data, 4); // now buffer is 1001

System.out.println(buffer.remainingBits()); // 16

byte[] datas = new byte[]{ (byte)210, 89 }; // 11010010 01011001
buffer.put(datas, 15); // This means put 15 bits into buffer, buffer is 10011101 00100101 100

System.out.println(buffer.remainingBits()); // 1

buffer.put(data, 2, 4); // This means put 4 bits into buffer, start position is 2
// now buffer is 10100101 00100101 100

System.out.println(buffer.remainingBits()); // 1, not change.

buffer.flip();

System.out.println(buffer.remainingBits()); // 19

希望有需要的同学都可以试用试用,有什么bug或者什么需求都可以反馈,我会尽量及时完善的。下一个版本我是想加上byte[]区从起始端bit取或者靠末尾端bit取的功能。

猜你喜欢

转载自xiaosunzhu.iteye.com/blog/2103415