將十六進制string轉成byte數(shù)組
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;?
? ? }?
? ? private static byte charToByte(char c) {?
? ? ? ? return (byte) "0123456789ABCDEF".indexOf(c);?
? ? }?
? ? private static String ByteArrayToHexString(byte[] data) //java可用
? ? {
? ? ? ? String result = "";
? ? ? ? for (int i = 0; i < data.length; i++)
? ? ? ? {
? ? ? ? ? ? String hex = Integer.toHexString(data[i] & 0xFF);
? ? ? ? ? ? if (hex.length() == 1)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? hex = "0" + hex;
? ? ? ? ? ? }
? ? ? ? ? ? result += hex.toUpperCase();
? ? ? ? }
? ? ? ? return result;
? ? }
? ? private static byte[] intToBytes2(int n) {?
? ? ? ? byte[] b = new byte[4];?
? ? ? ? for (int i = 0; i < 4; i++) {?
? ? ? ? ? ? b[i] = (byte) (n >> (24 - i * 8));?
? ? ? ? }?
? ? ? ? return b;?
? ? }?