BitSet 与 Byte Array 类型转化 转发

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.
// 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值