14

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

5
  • 1
    stackoverflow.com/questions/2137755/… Commented Oct 15, 2012 at 10:33
  • Do you want to do that in Java or C#? Commented Oct 15, 2012 at 10:36
  • java2s.com/Code/Java/Collections-Data-Structure/… Commented Oct 15, 2012 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? Commented Oct 15, 2012 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 Commented Oct 15, 2012 at 11:38

3 Answers 3

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++;
      }
  }
Sign up to request clarification or add additional context in comments.

Comments

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);

3 Comments

@MarkoTopolnik Didn't knew that. At first I thought you meant something else. Thanks. Edited. :)
And as a convenience, it is most practical to print an array's contents using Arrays.toString(array).
@MarkoTopolnik Okay. I always used array.toString() and got wierd HashCodes.. :( Thanks a million for that..
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.