?? e364. converting between a bitset and a byte array.txt
字號:
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;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -