简体   繁体   English

Java字符串,单个字符到十六进制字节

[英]Java String, single char to hex bytes

I want to convert a string by single char to 5 hex bytes and a byte represent a hex number: 我想将单个字符串转换为5个十六进制字节,一个字节表示十六进制数字:

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". 我尝试了下面的代码,但是当字符串太大时, Byte.decode出错,比如“4F”或“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);
}                

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

You can convert from char to hex String with String.format() : 您可以使用String.format()char转换为hex String

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

Or threat the char as an int and use: 或者将char作为int威胁并使用:

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

Use String hex = String.format("0x%02X", (int) array[i]); 使用String hex = String.format("0x%02X", (int) array[i]); to specify HexDigits with 0x before the string. 在字符串之前指定带有0x HexDigits。

A better solution is convert int into byte directly: 更好的解决方案是将int直接转换为byte

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

The Byte.decode() javadoc specifies that hex numbers should be on the form "0x4C" . Byte.decode()javadoc指定十六进制数字应位于"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 : 可能还有一种更简单的转换方法,因为String类有一个将字符串转换为字节的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM