删除最后一点字节



我有一个字节数组,例如(字节数组可以或小于3个字节)

byte[] array = {0b00000011, 0b00111011, 0b01010101}

i 如何删除字节的最后位:0B 0 0000011,0B 0 0111011,0B 0 1010101因为我想像这样的结果11 | 0111011 | 1010101但是我不知道该怎么做

还不清楚,但也许我理解:您想删除字节前面的所有不重要的位。您可以使用字符串;在伪代码中:

take a byte value N (or word or whatever)
prepare an empty string ST
while N<>0
  if (N & 1)
    then ST = "1"+ST
    else ST = "0"+ST
  N = N >> 1
end

现在,字符串st包含您想要的东西(如果是您想要的...)。

如果要保留领先的零,则可以执行此操作。

StringBuilder sb = new StringBuilder();
String sep = "";
for (byte b : bytes) {
    sb.append(sep);
    // set the top byte bit to 0b1000_0000 and remove it from the String
    sb.append(Integer.toBinaryString(0x80 | (b & 0x7F)).substring(1));
    sep = '|';
}
String s = sb.toString();
    byte[] array = { 0b00000011, 0b00111011, 0b01010101 };
    int result = 0;
    for (byte currentByte : array) {
        result <<= 7; // shift
        result |= currentByte & 0b0111_1111;
    }
    System.out.println(Integer.toBinaryString(result));

此打印:

1101110111010101

如果您的数组长于4个字节,则可能是未检测到的int溢出。

最新更新