java二进制和十六进制的相互转换
程序员文章站
2022-03-13 15:46:54
...
/**
* 二进制转十六进制
* @param sb
* @param polynthic1
* @return
*/
private static int turnToHex(int[] polynthic1) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < polynthic1.length; i++) {
sb.append(polynthic1[i]);
}
int keyTen = Integer.parseInt(sb.toString(), 2); // 2->10
String result = String.format("%X", keyTen);
byte by = (byte) Integer.parseInt(result, 16); // string->byte
int ten = by & 0xff; // byte->int
return ten;
}
/**
* 十六进制转二进制
* @param hex 十六进制数
* @return 二进制数
*/
private static int[] turnTwo(int hex) {
int tenNum = Integer.parseInt(Integer.toHexString(hex).toUpperCase(), 16);
String str = "";
while (tenNum != 0) {
str = tenNum % 2 + str;
tenNum /= 2;
}
int[] ans = new int[8];
for (int i : ans) {
i = 0;
}
for (int i = 0; i < str.length(); i++) {
ans[i] = str.charAt(i) - '0';
}
return ans;
}