您的位置:首页 > 其它

BitSet 与 Byte Array 类型转化 转发

2012-08-01 11:14 134 查看


Converting Between
a BitSet and a Byte Array

There are no default methods for converting a BitSet to and from a byte array. This example implements two methods to do the conversion. These methods
make it possible to easily work with both BitSet and BigInteger and take advantage of their capabilities
when needed.

COPY
// Returns a bitset containing the values in bytes.
// The byte-ordering of bytes must be big-endian which means the most significant bit is in element 0.
public static BitSet fromByteArray(byte[] bytes) {
BitSet bits = new BitSet();
for (int i=0; i<bytes.length*8; i++) {
if ((bytes[bytes.length-i/8-1]&(1<<(i%8))) > 0) {
bits.set(i);
}
}
return bits;
}

// Returns a byte array of at least length 1.
// The most significant bit in the result is guaranteed not to be a 1
// (since BitSet does not support sign extension).
// The byte-ordering of the result is big-endian which means the most significant bit is in element 0.
// The bit at index 0 of the bit set is assumed to be the least significant bit.
public static byte[] toByteArray(BitSet bits) {
byte[] bytes = new byte[bits.length()/8+1];
for (int i=0; i<bits.length(); i++) {
if (bits.get(i)) {
bytes[bytes.length-i/8-1] |= 1<<(i%8);
}
}
return bytes;
}

//Comments

10 Dec 2010 - 1:46pm by Anonymous (not verified)
Please be aware the above example will lose 1 bit for every byte read if the highest order bit is set. (byte)(1<<7) = -128 in Java and therefore will never be >0. To fix this example change >0 to !=0.Also, it would be easy and preferable to serialize to longs as the Java implementation does.
16 Feb 2011 - 12:08pm by Anonymous (not verified)
Note that the Java 7 specification provides methods for converting between BitSets and bytes/longs.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: