Remove last bit of byte

3.1k Views Asked by At

I have a byte array, for example (byte array can be more or less than 3 bytes)

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

How can I remove the last bit of bytes: 0b00000011, 0b00111011, 0b01010101 because I want to get result like this 11|0111011|1010101 but I have no idea how to do that

3

There are 3 best solutions below

0
On

It is not really clear, but perhaps I understand: you want to remove all the non-significant bits in front of a byte. You could use a string for that; in pseudo-code:

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

Now the string ST contains what you want (if is that that you want...).

0
On

If you want to retain leading zeros you can do this.

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();
0
On
    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));

This prints:

1101110111010101

If your array is longer than 4 bytes, an undetected int overflow is likely.