11

I want to convert a string by single char to 5 hex bytes and a byte represent a hex number:

like

String s = "ABOL1";

to

byte[] bytes = {41, 42, 4F, 4C, 01}

I tried following code , but Byte.decode got error when string is too large, like "4F" or "4C". Is there another way to convert it?

String s = "ABOL1";
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
  String hex = String.format("%02X", (int) array[i]);
  bytes[i] = Byte.decode(hex);
}                
2
  • 1
    A char is not a byte! Commented Apr 28, 2015 at 8:08
  • 2
    There is no such thing as a 'hex byte'. The data is already in the format you require. Just copy the bytes. Commented Apr 28, 2015 at 10:01

4 Answers 4

5

Is there any reason you are trying to go through string? Because you could just do this:

bytes[i] = (byte) array[i];

Or even replace all this code with:

byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);
Sign up to request clarification or add additional context in comments.

Comments

3

You can convert from char to hex String with String.format():

String hex = String.format("%04x", (int) array[i]);

Or treat the char as an int and use:

String hex = Integer.toHexString((int) array[i]);

1 Comment

@Mathias - why did you remove the (int) cast in the first snippet - so it will fail at execution time! %04x does not accept a Character (from char[] array as given in question) PLEASE avoid changing code if not for simply (obvious) typos!!!
2

Use String hex = String.format("0x%02X", (int) array[i]); to specify HexDigits with 0x before the string.

A better solution is convert char into byte directly:

bytes[i] = (byte)array[i];

a char is an integral type in Java

1 Comment

but please consider that this only correctly works for the first 256 char( \u0000 to \u00FF)
-1

The Byte.decode() javadoc specifies that hex numbers should be on the form "0x4C". So, to get rid of the exception, try this:

String hex = String.format("0x%02X", (int) array[i]);

There may also be a simpler way to make the conversion, because the String class has a method that converts a string to bytes :

bytes = s.getBytes();

Or, if you want a raw conversion to a byte array:

int i, len = s.length();
byte bytes[] = new byte[len];
String retval = name;
for (i = 0; i < len; i++) {
    bytes[i] = (byte) name.charAt(i);
}

Comments

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.