java 以字符串获取的数组,怎么转成16位字符串?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 以字符串获取的数组,怎么转成16位字符串?相关的知识,希望对你有一定的参考价值。
String msg="[104,-62,57,-106,119,81,32,71,102,-48,-71,38,0,8,8,0,0,-18,-18,-18,-18,-18,-18,-18,-18,-18,-18,19,23,22,18,34,36,32,70,52,69,48,48,8,8,-12,-4,40,0,0,0,1,-18,-18,-18,-94,-64,22]";
这个是获取的字符串,该怎么转成16进制字符串呢?
或者转化成
byte msgs[]=
104,-62,57,-106,119,81,32,71,102,-48,-71,38,0,8,8,0,0,-18,-18,-18,-18,-18,-18,-18,-18,-18,-18,19,23,22,18,34,36,32,70,52,69,48,48,8,8,-12,-4,40,0,0,0,1,-18,-18,-18,-94,-64,22
也可以
String hexString = "";
for (int i = 0; i < msg.length; i++)
int num = Integer.parseInt(msg[i]);
String hex = Integer.toHexString(num);
hexString += hex;
System.out.println(hexString); 参考技术B 方法一:
String[] arr = msg.split(",");
StringBuilder sb = new StringBuilder();
for (String str : arr)
int value = Integer.parseInt(str.trim());
sb.append(Integer.toHexString(value)).append(" ");
String hexStr = sb.toString();
System.out.println(hexStr);
方法二:
String[] arr = msg.split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++)
String hexStr = Integer.toHexString(Integer.valueOf(arr[i]));
sb.append(hexStr).append(" ");
System.out.println(sb.toString()); 参考技术C String[] strArray = new String[]"a","b","c";StringBuilder sb = new StringBuilder();for (String str : strArray) sb.append(String.format("%016x", new BigInteger(1, str.getBytes())));String hexStr = sb.toString();System.out.println(hexStr); 参考技术D
你可以使用以下步骤将字符串 msg 转换为16进制字符串:
将字符串 msg 转换为字节数组,可以使用 Arrays.toString(msg.getBytes())
将字节数组中每个字节转换为 16 进制字符串,可以使用 Integer.toHexString(byteValue)
将转换后的字符串拼接起来得到最终的16进制字符串
例如:
byte[] bytes = msg.getBytes();
StringBuilder hexString = new StringBuilder();
for (byte b : bytes)
hexString.append(Integer.toHexString(b & 0xff));
String result = hexString.toString();
注意:转换后的字符串可能会有一些前导0,如果需要去掉可以使用 string.replaceFirst("^0+(?!$)", "")
netty bytebuf怎么转成byte数组
ByteBuf buf = (ByteBuf)msg;byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req,"UTF-8"); 参考技术A byte[] bytes = ByteBufUtil.getBytes(byteBuf);
ByteBufUtil,netty自带的工具类.
以上是关于java 以字符串获取的数组,怎么转成16位字符串?的主要内容,如果未能解决你的问题,请参考以下文章