1

Need to reverse all the bits in a byte []. I'm doing this in two steps.

  1. Reverse all the bytes in this array.
  2. Reverse all the bits in each byte.

Is this the most efficient way to do this?

public byte[] reverse(byte [] data) {
    byte [] bytes = data.clone();
    for (int i = 0; i < bytes.length / 2; i++) {
        byte temp = bytes[i];
        bytes[i] = bytes[bytes.length - i - 1];
        bytes[bytes.length - i - 1] = temp;
    }
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = (byte) (Integer.reverse(bytes[i]) >>> 24)
    }
    return bytes;
}
  1. The flipping is used as a primitive hashing function.
  2. I realized that I was flipping the bits not reversing them, this has been fixed.
  3. The bitwise '&' was unnecessary and has been removed.
smahesh
  • 663
  • 1
  • 11
  • 21
  • 1
    Why do you need to reverse even the single bits inside each byte? – Jack Jun 11 '14 at 17:06
  • idk about the bits, but shouldn't you split this into two methods? reverseBytes(byte[] data) and reverseBits(byte[] data)? – Kyte Jun 11 '14 at 17:16
  • 7
    In addition your reverse operation is not reversing the order, but just flipping the byte (inverting). What do you need? – Jack Jun 11 '14 at 17:18
  • 1
    Why do you need to `& 0xFF` if you're going to cast to `byte` anyways? – awksp Jun 11 '14 at 17:19
  • 2
    If you need to _reverse_ order of bits (not inverse byte value), you can pre-calculate lookup table of 256 elements. – Victor Sorokin Jun 11 '14 at 17:22
  • If you need to reverse the order of bits, you could use `Integer.reverse(bytes[i]) >>> 24`. – Louis Wasserman Jun 11 '14 at 17:42

0 Answers0