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);
}
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]);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With