kar*_*raj 1 java encryption android java-security android-security
我正在尝试将 byte[] 转换为十六进制字符串,并将相同的十六进制字符串转换为 android 中的 byte[] ,数据不匹配。
前任 :
收到字节[]数据:[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;
}
Run Code Online (Sandbox Code Playgroud)
我使用以下内容并且它们有效。
/**
* Converts byte array to hex string
*
* @param bytes The data
* @return String represents the data in HEX string
*/
public static String byteArrayToHexString(final byte[] bytes) {
StringBuilder sb = new StringBuilder();
for(byte b : bytes){
sb.append(String.format("%02x", b&0xff));
}
return sb.toString();
}
/**
* Converts hex string to byte array
*
* @param s The data in string
* @return byte represents the string in bytes
*/
public static byte[] hexStringToByteArray(final String s) {
if (s == null) {
return (new byte[]{});
}
if (s.length() % 2 != 0 || s.length() == 0) {
return (new byte[]{});
}
byte[] data = new byte[s.length() / 2];
for (int i = 0; i < s.length(); i += 2) {
try {
data[i / 2] = (Integer.decode("0x" + s.charAt(i) + s.charAt(i + 1))).byteValue();
} catch (NumberFormatException e) {
return (new byte[]{});
}
}
return data;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12664 次 |
| 最近记录: |