Java - 将Big-Endian转换为Little-Endian

时间:2015-09-21 10:52:58

标签: java hex bitcoin endianness

我有以下十六进制字符串:

  

00000000000008a3a41b85b8b29ad444def299fee21793cd8b9e567eab02cd81

但我希望它看起来像这样:

  

81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000(大   端)

我想我必须反转并交换字符串,但这样的事情并没有给我正确的结果:

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

结果:   81dc20bae765e9b8dc39712eef992fed444da92b8b58b14a3a80000000000000   (错误)   81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000   (应该是)

交换:

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

结果:   026053973026883595670517176393898043396144045912271014791797784   (错误)   81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000   (应该是)

有人能举例说明如何做到这一点吗? 非常感谢你:))

1 个答案:

答案 0 :(得分:2)

您需要交换每个字符,因为您正在反转字节的顺序,而不是nybbles。如下所示:

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