Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the byte array in java? [duplicate]

Tags:

java

Possible Duplicate:
How do I reverse an int array in Java?

What is the equivalent function in java to perform Array.Reverse(bytearray) in C# ?

like image 970
sat Avatar asked Oct 15 '12 10:10

sat


People also ask

How do you reverse bytes in Java?

Integer reverseBytes() Method in Java The java. lang. Integer. reverseBytes(int a) is a built-in method which returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified int value.

How do you reverse bytes?

Efficient approach: The idea is to use shift operators only. Move the position of the last byte to the first byte using left shift operator(<<). Move the position of the first byte to the last byte using right shift operator(>>). Move the middle bytes using the combination of left shift and right shift operator.


2 Answers

public static void reverse(byte[] array) {
      if (array == null) {
          return;
      }
      int i = 0;
      int j = array.length - 1;
      byte tmp;
      while (j > i) {
          tmp = array[j];
          array[j] = array[i];
          array[i] = tmp;
          j--;
          i++;
      }
  }
like image 96
Jainendra Avatar answered Sep 22 '22 19:09

Jainendra


You can use Collections.reverse on a list returned by Arrays.asList operated on an Array: -

    Byte[] byteArr = new Byte[5];

    byteArr[0] = 123; byteArr[1] = 45;
    byteArr[2] = 56;  byteArr[3] = 67;
    byteArr[4] = 89;

    List<Byte> byteList = Arrays.asList(byteArr); 

    Collections.reverse(byteList);  // Reversing list will also reverse the array

    System.out.println(byteList);
    System.out.println(Arrays.toString(byteArr));

OUTPUT: -

[89, 67, 56, 45, 123]
[89, 67, 56, 45, 123] 

UPDATE: - Or, you can also use: Apache Commons ArrayUtils#reverse method, that directly operate on primitive type array: -

byte[] byteArr = new byte[5];
ArrayUtils.reverse(byteArr);
like image 22
Rohit Jain Avatar answered Sep 23 '22 19:09

Rohit Jain