0

I have a device sending me their IP address in hexadecimal form through a udp packet. I want to print out that IP address in the form that it came in. FF FF FF FF for example.

But I'm not sure how to do that, and my code won't work because it just turns everything into the unreadable UTF-8 symbol.

byte[] ipAddr = {(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF};
String ipString = new String(ipAddr, StandardCharsets.UTF_8);

How can I change the code so that printing ipString gives "FF FF FF FF"?

qol
  • 41
  • 1
  • 5
  • 1
    Does this answer your question? [How to convert a byte array to a hex string in Java?](https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java) – Marcono1234 Sep 25 '20 at 20:42
  • The sample code fails because the data is not UTF-8, yet you claim (in the string constructor) that it is UTF-8. – J.Backus Sep 26 '20 at 01:12

1 Answers1

0

You can use a ByteBuffer to convert the 4 bytes to an int, then use String.format() to format that in hexadecimals with leading zeroes, like this:

byte[] ipAddr = {(byte)0xFC, (byte)0xFD, (byte)0xFE, (byte)0xFF};

int ipInt = ByteBuffer.wrap(ipAddr).order(ByteOrder.BIG_ENDIAN).getInt();
String ipString = String.format("%08x", ipInt).toUpperCase();

System.out.println(ipString);

Output

FCFDFEFF
Andreas
  • 154,647
  • 11
  • 152
  • 247