Tess Christensen
Tess Christensen

Reputation: 11

Converting a byte[] to a String in Java

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!

Upvotes: 0

Views: 120

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533442

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);

Upvotes: 2

Related Questions