Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String, single char to hex bytes

Tags:

java

hex

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);
}                
like image 538
Sarah0050 Avatar asked Apr 28 '15 08:04

Sarah0050


2 Answers

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

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

Or threat the char as an int and use:

String hex = Integer.toHexString((int) array[i]);
like image 130
Jordi Castilla Avatar answered Nov 01 '22 17:11

Jordi Castilla


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);
like image 44
weston Avatar answered Nov 01 '22 17:11

weston