Java中byte與16進制字符串的互相轉換
阿新 • • 發佈:2018-08-17
ring ati case nbsp i++ 轉換成 con htm uil
https://www.cnblogs.com/qinwangchen/p/5418028.html
* Convert byte[] to hex string.這裏我們可以將byte轉換成int,然後利用Integer.toHexString(int)來轉換成16進制字符串。 * @param src byte[] data * @return hex string */ public static String bytesToHexString(byte[] src){ StringBuilder stringBuilder = new StringBuilder("");if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); }return stringBuilder.toString(); } /** * Convert hex string to byte[] * @param hexString the hex string * @return byte[] */ public static byte[] hexStringToBytes(String hexString) { if (hexString == null || hexString.equals("")) { return null; } hexString = hexString.toUpperCase();int length = hexString.length() / 2; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; } /** * Convert char to byte * @param c char * @return byte */ private byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); }
java中byte轉換int時為何與0xff進行與運算?看原著
Java中byte與16進制字符串的互相轉換