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.
6
  • 1
    Why do you need to reverse even the single bits inside each byte? Commented Jun 11, 2014 at 17:06
  • idk about the bits, but shouldn't you split this into two methods? reverseBytes(byte[] data) and reverseBits(byte[] data)? Commented Jun 11, 2014 at 17:16
  • 7
    In addition your reverse operation is not reversing the order, but just flipping the byte (inverting). What do you need? Commented Jun 11, 2014 at 17:18
  • 1
    Why do you need to & 0xFF if you're going to cast to byte anyways? Commented Jun 11, 2014 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. Commented Jun 11, 2014 at 17:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.