12

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# ?

Community
  • 1
  • 1
sat
  • 14,589
  • 7
  • 46
  • 65
  • 1
    http://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java – Alex Oct 15 '12 at 10:33
  • Do you want to do that in Java or C#? – Rohit Jain Oct 15 '12 at 10:36
  • http://www.java2s.com/Code/Java/Collections-Data-Structure/Reversestheorderofthegivenbytetypearray.htm – maxstreifeneder Oct 15 '12 at 10:37
  • Can you say why you need to do this because if you want to switch between little endian and big endian there are much better ways of doing this? – Peter Lawrey Oct 15 '12 at 10:51
  • Actually, we are trying to decrypt the .net encrypted string(RSA).In that, we faced some padding issue.To resolve, we wanted to reverse the byte array.For more information click [here](http://stackoverflow.com/questions/12543933/bad-padding-exception-in-java-rsa-decryption) – sat Oct 15 '12 at 11:38

3 Answers3

22
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++;
      }
  }
Jainendra
  • 24,713
  • 30
  • 122
  • 169
14

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);
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

You may use java.util.Collections.reverse(). It takes java.util.List as an input argument. So you should convert your byteArray into a List either by doing Arrays.asList(byteArray) or by creating an List object and adding byte values into it.

sakthisundar
  • 3,278
  • 3
  • 16
  • 29