gpt4 book ai didi

Java - 将大端转换为小端

转载 作者:行者123 更新时间:2023-11-30 08:46:57 29 4
gpt4 key购买 nike

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

00000000000008a3a41b85b8b29ad444def299fee21793cd8b9e567eab02cd81

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

81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000 (Big endian)

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

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

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

交换:

    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)

任何人都可以给我一个如何完成这个的例子吗?非常感谢:)

最佳答案

您需要交换每 个字符,因为您要颠倒字节的顺序,而不是 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);
}

关于Java - 将大端转换为小端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32693406/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com