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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29913785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:07:17  来源:igfitidea点击:

Java String, single char to hex bytes

javahex

提问by Sarah0050

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.decodegot error when string is too large, like "4F" or "4C". Is there another way to convert it?

我尝试了以下代码,但是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);
}                

采纳答案by locoyou

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

用于在字符串之前String hex = String.format("0x%02X", (int) array[i]);指定 HexDigits 0x

A better solution is convert intinto bytedirectly:

更好的解决方案是直接转换intbyte

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

回答by weston

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

回答by Jordi Castilla

You can convert from charto hex Stringwith String.format():

您可以使用String.format()将其转换char为十六进制:String

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

Or threat the charas an intand use:

或威胁charas anint并使用:

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

回答by Klas Lindb?ck

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

Byte.decode()的javadoc指定在十六进制数应在表格上"0x4C"。因此,要摆脱异常,请尝试以下操作:

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 的方法:

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