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!

5
  • 1
    Show your own effort and code to solve the problem (as properly formatted text in the question) Commented Oct 6, 2018 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? Commented Oct 6, 2018 at 12:33
  • 1
    Possible duplicate of Java code To convert byte to Hexadecimal Commented Oct 6, 2018 at 12:40
  • stackoverflow.com/questions/2817752/… Commented Oct 6, 2018 at 12:48
  • use Integer.toHexString(data[i]); instead of data[i] in the loop Commented Oct 6, 2018 at 13:37

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! For this particular assignment, we only need it to work for 0 to 15, so that's exactly what I need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.