hex - Java - Convert Big-Endian to Little-Endian -
i have following hex string:
00000000000008a3a41b85b8b29ad444def299fee21793cd8b9e567eab02cd81
but want this:
81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000 (big endian)
i think have reverse , swap string, 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 number hex biginteger orig = new biginteger(orighex,16); // bytes swap byte[] origbytes = orig.tobytearray(); int = 0; while(origbytes[i] == 0) i++; // swap bytes byte[] swapbytes = new byte[origbytes.length]; for(/**/; < origbytes.length; i++) { swapbytes[i] = origbytes[origbytes.length - - 1]; } biginteger swap = new biginteger(swapbytes); return swap.tostring(10); } hex = hexswap(hex);
result: 026053973026883595670517176393898043396144045912271014791797784 (wrong) 81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000 (should be)
can give me example of how accomplish this? thank lot :)
you need swap each pair of characters, you're reversing order of bytes, not nybbles. like:
public static string reversehex(string originalhex) { // todo: validation length int lengthinbytes = originalhex.length() / 2; char[] chars = new char[lengthinbytes * 2]; (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); }
Comments
Post a Comment