1

I'm trying to get hex string value from bytebuffer using below code. Reference: In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

    public ByteBuffer convert(ByteBuffer in) {
    StringBuffer out = new StringBuffer();
    for (int iter = 0; iter < in.array().length; iter++) {
      byte high = (byte) ( (in.array()[iter] & 0xf0) >> 4);
      byte low =  (byte)   (in.array()[iter] & 0x0f);
      out.append(nibble2char(low));
      out.append(nibble2char(high));
    }
    return ByteBuffer.wrap(out.reverse().toString().getBytes());
   }
   private static char nibble2char(byte b) {
   byte nibble = (byte) (b & 0x0f);
   if (nibble < 10) {
     return (char) ('0' + nibble);
   }
   return (char) ('a' + nibble - 10);
  }

The value I got as 701000000000, Actually I'm expecting a value like this 000000000107. So I called a reverse method on stringbuffer object at the time of wrapping.

After this I'm always getting "ffffff000000" Can someone please help me on this.

Ganesh
  • 91
  • 2
  • 9
  • Take a look at [this](https://stackoverflow.com/a/9855338/10934377) answer. – Heiko Ribberink Feb 23 '22 at 10:02
  • @HeikoRibberink I tried it, but getting the result as '070100000000' – Ganesh Feb 23 '22 at 11:22
  • char[] hexChars = new char[in.array().length * 2]; for (int j = in.array().length-1; j >= 0; j--) { int v = in.array()[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } out.append(new String(hexChars)); – Ganesh Feb 23 '22 at 11:23
  • You could loop over it in reverse order, by changing the for-loop. – Heiko Ribberink Feb 23 '22 at 12:20
  • Like this: ```for (int j = bytes.length - 1; j > 0; j--) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 - 1] = HEX_ARRAY[v & 0x0F]; }``` Haven't tested it, but I think it'll work. – Heiko Ribberink Feb 23 '22 at 12:24
  • Sorry for the hopeless formatting btw, I thought code blocks would work in comments, but they obviously don't. – Heiko Ribberink Feb 23 '22 at 12:29

0 Answers0