我想将单个字符串转换为5个十六进制字节,一个字节表示十六进制数字:
喜欢
String s = "ABOL1";
Run Code Online (Sandbox Code Playgroud)
至
byte[] bytes = {41, 42, 4F, 4C, 01}
Run Code Online (Sandbox Code Playgroud)
我尝试了下面的代码,但是Byte.decode当字符串太大时出错,比如"4F"或"4C".还有另一种转换方法吗?
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);
}
Run Code Online (Sandbox Code Playgroud)
你是否有任何理由试图通过字符串?因为你可以这样做:
bytes[i] = (byte) array[i];
Run Code Online (Sandbox Code Playgroud)
甚至用以下代码替换所有这些代码:
byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);
Run Code Online (Sandbox Code Playgroud)
用于在字符串之前String hex = String.format("0x%02X", (int) array[i]);指定 HexDigits 。0x
更好的解决方案是直接转换int为byte:
bytes[i] = (byte)array[i];
Run Code Online (Sandbox Code Playgroud)