[英]Format String as an hex value and append it in char array
我有以下代码。
String test1 = "10";
String result = String.format("%02X", test1);
char buffer[] = {result.charAt(0),0x01,0x00,0x01,0x00,0x20};
byte[] bufferbyte = new String(buffer).getBytes();
for (byte b : bufferbyte){
System.out.format("0X%x ", b);
}
实际上,字符串变量“ test1”包含十进制值。 我的意思是说用户可以输入1 -256个整数,并将其存储在“ test1”中。 我以10为例。 我需要将其十六进制值(0A)附加在char数组的第一个位置“缓冲区”中,并将其显示为包含十六进制值的字节数组。
上面的代码显示错误为
"Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String"
尝试这个
String result = String.format("%02X", Integer.parseInt(test1));
public class SSCCE
{
public static void main(final String[] args)
{
final String ten = "10";
final Integer i = Integer.parseInt(ten);
System.out.format("%02X", i);
}
}
输出0A
您正在尝试格式化String
您需要格式化Integer
表示形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.