【发布时间】:2017-04-15 21:52:53
【问题描述】:
我正在尝试将 byte[] 转换为 Hex 字符串,并将相同的 Hex 字符串转换为 byte[] 在 android 中,数据不匹配。
例如:
接收到的字节[]数据:[B@b39c86a
转换后的十六进制字符串:8be897cc3c4d9e5dd6a6bbd106d8e8d487691b56
当我解码十六进制字符串时,我得到 [B@ea6d15b,但它应该是 [B@b39c86a
我正在使用下面的代码进行转换。
public String byte2hex(byte[] a) {
/*StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();*/
String hexString = "";
for(int i = 0; i < a.length; i++){
String thisByte = "".format("%x", a[i]);
hexString += thisByte;
}
return hexString;
}
public static byte[] hexStringToByteArray(String s) {
/* int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;*/
byte[] bytes = new byte[s.length() / 2];
for(int i = 0; i < s.length(); i += 2){
String sub = s.substring(i, i + 2);
Integer intVal = Integer.parseInt(sub, 16);
bytes[i / 2] = intVal.byteValue();
String hex = "".format("0x%x", bytes[i / 2]);
}
return bytes;
}
【问题讨论】:
-
[B@b39c86a。不,那不是字节数据。这是 bytes.toString() 的值。不是字节的内容。但是你在开始你的帖子时没有向我们展示你是如何来到这个字符串的。此外,您没有显示如何调用函数以及使用哪些参数。你说'我得到',但不要显示它的代码或你如何打印/记录它。请发布完整的示例。 -
@greenapps 我正在使用 GATT 服务,从 onCharacteristicChanged() 表格中我收到的值是 byte[]。请在下面找到我的代码。字符串 ss= byte2hex(characteristic.getValue());字节[] bt= hexStringToByteArray(ss); Log.d(TAG,"onCharacteristicChanged UUID 1::"+ss); Log.d(TAG,"onCharacteristicChanged UUID 2:: "+bt);
-
please find my code below.。我什至不会尝试阅读。当然,您应该在帖子中发布所有代码。这是不可读的!你喜欢看cmets里的代码吗?
标签: java android encryption android-security java-security