String类型转十六进制byte数组
public static byte[] String2Byte(String s) { s = s.replace(" ", ""); s = s.replace("#", ""); byte[] baKeyword = new byte[s.length() / 2]; for (int i = 0; i < baKeyword.length; i++) { try { baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16)); } catch (Exception e) { e.printStackTrace(); } } return baKeyword; }
int 类型转十六进制byte数组
String hexString = Integer.toHexString(405);
如上代码得到的结果:
195
Process finished with exit code 0
总上所述,int类型转十六进制得到的是String类型十六进制,将String类型转为真正的十六进制byte[]数组,.getBytes()方法是不可行的。
利用一开始的String转byte会导致数据不一致,所以处理了一下:
1 public static String intToHex(int val){ 2 3 String s = Integer.toHexString(val); 4 if (s.length() % 2 != 0) { 5 s = "0" + s; 6 } 7 return Utilty.byte2String(Utilty.string2Byte(s)); 8 }
byte数组转换16进制字符串:
1 public static String byte2String(byte[] data) { 2 char[] hexArray = "0123456789ABCDEF".toCharArray(); 3 char[] hexChars = new char[data.length * 2]; 4 5 for (int j = 0; j < data.length; j++) { 6 int v = data[j] & 0xFF; 7 hexChars[j * 2] = hexArray[v >>> 4]; 8 hexChars[j * 2 + 1] = hexArray[v & 0x0F]; 9 } 10 11 String result = new String(hexChars); 12 result = result.replace(" ", ""); 13 return result; 14 }
byte数组转换ASCII码字符串:
byte[] byte = new byte[10]; String str = new String(bytes);
byte数组转int类型,先将byte数组转换成十六进制字符串。
byte[] bytes = new byte[10]; String byteStr = byte2Sting(bytes); int num = Integer.parseInt(byteStr,16);