[英]BitSet and Byte Array value getting SET from opposite direction
我有:
public byte[] bytes = new byte[5]; //BitComp Class
public BitSet bits = new BitSet(40);
class 中的 getter 和 setter 名為 BitComp。 下面的 class 將所有前 8 位設置為 1(byte[0])。之后,它將所有字節轉換為 BitSet。 現在,當它將第二位設置為 true 並打印它們時。
import java.util.BitSet;
public class TestBitSet {
public void testBit(){
BitComp comp = new BitComp();
comp.bytes[0] |= 0xFF;
comp.setBits(getBitsFromByte(comp.getBytes()));
System.out.println(toCharArray(comp.getBits()));
BitSet bs = comp.getBits();
bs.set(1,true);
comp.setBits(bs);
System.out.println(toCharArray(comp.getBits()));
}
private BitSet getBitsFromByte(byte[] barray)
{
BitSet bits=new BitSet();
if(barray!=null)
{
for (int i=0; i<barray.length*8; i++)
{
if ((barray[barray.length-i/8-1]&(1<<(i%8)))!= 0)
{
bits.set(i);
}
}
}
return bits;
}
public static char[] toCharArray(final BitSet bs)
{
final int length = bs.length();
final char[] arr = new char[length];
for(int i = 0; i < length; i++)
{
arr[i] = bs.get(i) ? '1' : '0';
}
return arr;
}
public static void main(String args[]){
TestBitSet tbs = new TestBitSet();
tbs.testBit();
}
}
Output:0000000000000000000000000000000011111111 <- 0th
第0-> 01000000000000000000000000000000011111111
不應該有任何變化,因為 byte[0] 包含前 8 個元素,我使用 BitSet 操作將第二個元素設置為 1。 所以 BitSet 是從 LHS 接近的,而 Byte 數組是從 RHS 存儲的。 如何解決這個問題? getBitsFromByte 方法有問題嗎? 請建議。 謝謝
只需在您的集合中添加一點數學: ((byteNumber*8)+(7-bitNumber))
您沒有提供 BitComp 的代碼,但在我看來,您決定了如何將位轉換為字節以及打印字節的順序。
它完全取決於你什么命令你什么東西要設置或打印出來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.