簡體   English   中英

用Java檢查字節數組中的各個位?

[英]Checking individual bits in a byte array in Java?

所以說我有一個字節數組,並且我有一個函數來檢查字節數組的第n個最低有效位索引是1還是0.如果該位是1則返回true,如果該位則返回false字節數組的最低有效位定義為字節數組第0個索引中的最后一個有效位,字節數組的最高有效位定義為(字節數組中的最高有效位)。 length - 1)字節數組的索引。

例如,

byte[] myArray = new byte[2];
byte[0] = 0b01111111;
byte[1] = 0b00001010;

呼叫:

myFunction(0) = true;
myFunction(1) = true;
myFunction(7) = false;
myFunction(8) = false;
myFunction(9) = true;
myFunction(10) = false;
myFunction(11) = true;

做這個的最好方式是什么?

謝謝!

您可以使用此方法:

public boolean isSet(byte[] arr, int bit) {
    int index = bit / 8;  // Get the index of the array for the byte with this bit
    int bitPosition = bit % 8;  // Position of this bit in a byte

    return (arr[index] >> bitPosition & 1) == 1;
}

bit % 8是相對於byte的位位置。
arr[index] >> bit % 8index處的位移動到位0位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM