0

Say we have a byte[] array:

byte[] data = {10,10,1,1,9,8}

and I want to convert these values in to a hexadecimal string:

String arrayToHex = "AA1198"

How can I do this? Using Java language in IntelliJ. Keep in mind this is my first semester of coding, so I'm already feeling lost.

First I start with this method:

public static String toHexString(byte[] data)

In the problem I'm trying to solve, we get a string from a user input, which is then converted to a byte[] array, and from there must be converted back into a string in hexadecimal format. But for simplification purposes I am just trying to input my own array. So, here I have my array:

byte[] data = {10,10,1,1,9,8}

I know how to just print the byte array by just saying:

for (int i = 0; i < data.length; i++)
{
  System.out.print(data[i]);
}

which will have an output of:

10101198

but obviously this is not what I'm looking for, as I have to convert the 10s to As, and I need a String type, not just an output. I'm sorry I'm so vague, but I'm truly lost and ready to give up!

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
  • 1
    Show your own effort and code to solve the problem (as properly formatted text in the question) – Michael Butscher Oct 06 '18 at 12:30
  • 1
    Should 10 really map to just A, not 0A? What should happen with value that have an upper nibble different from zero? – harold Oct 06 '18 at 12:33
  • 1
    Possible duplicate of [Java code To convert byte to Hexadecimal](https://stackoverflow.com/questions/2817752/java-code-to-convert-byte-to-hexadecimal) – S.K. Oct 06 '18 at 12:40
  • https://stackoverflow.com/questions/2817752/java-code-to-convert-byte-to-hexadecimal – jker Oct 06 '18 at 12:48
  • use Integer.toHexString(data[i]); instead of data[i] in the loop – Joe Oct 06 '18 at 13:37

1 Answers1

2

This is not what you would normally do and would only work for byte values from 0 to 15.

byte[] data = {10,10,1,1,9,8};
StringBuilder sb = new StringBuilder();
for (byte b : data)
    sb.append(Integer.toHexString(b));
String arrayAsHex = sb.toString();

What you would normally expect is "0A0A01010908" so that any byte value is possible.

String arrayAsHex = DatatypeConverter.printHexBinary(data);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130