Java Convert Big Endian to Little Endian

I have the following hex string:

00000000000008a3a41b85b8b29ad444def299fee21793cd8b9e567eab02cd81

but I want it to look like this:

81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000 (Big endian)

I think I have to reverse and swap the string, but something like this doesn't give me right result:

  String hex = "00000000000008a3a41b85b8b29ad444def299fee21793cd8b9e567eab02cd81";
    hex = new StringBuilder(hex).reverse().toString();

Result: 81dc20bae765e9b8dc39712eef992fed444da92b8b58b14a3a80000000000000 (wrong) 81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000 (should be)

The swapping:

    public static String hexSwap(String origHex) {
        // make a number from the hex
        BigInteger orig = new BigInteger(origHex,16);
        // get the bytes to swap
        byte[] origBytes = orig.toByteArray();
        int i = 0;
        while(origBytes[i] == 0) i++;
        // swap the bytes
        byte[] swapBytes = new byte[origBytes.length];
        for(/**/; i < origBytes.length; i++) {
            swapBytes[i] = origBytes[origBytes.length - i - 1];
        }
        BigInteger swap = new BigInteger(swapBytes);
        return swap.toString(10);
    }

hex = hexSwap(hex);

Result: 026053973026883595670517176393898043396144045912271014791797784 (wrong) 81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000 (should be)

Can anyone give me a example of how to accomplish this? Thank you a lot :)

Jon Skeet
people
quotationmark

You need to swap each pair of characters, as you're reversing the order of the bytes, not the nybbles. So something like:

public static String reverseHex(String originalHex) {
    // TODO: Validation that the length is even
    int lengthInBytes = originalHex.length() / 2;
    char[] chars = new char[lengthInBytes * 2];
    for (int index = 0; index < lengthInBytes; index++) {
        int reversedIndex = lengthInBytes - 1 - index;
        chars[reversedIndex * 2] = originalHex.charAt(index * 2);
        chars[reversedIndex * 2 + 1] = originalHex.charAt(index * 2 + 1);
    }
    return new String(chars);
}

people

See more on this question at Stackoverflow