把十六进制的位串转化为byte数组

方式一:

/** 
	 * 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;  
	    }  
 if(hexString.length()%2!=0){  
            throw new RuntimeException("Hex  bit string length must be even");  
        } 
	    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
	 * 'F'-->15
	 * @param c
	 *            char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		int index = "0123456789ABCDEF".indexOf(c);
		if (index == -1) {
			index = "0123456789abcdef".indexOf(c);
		}
		return (byte) index;
	}

 

方式二:

// 从十六进制字符串到字节数组转换
	 public static byte[] hexString2Bytes(String hexstr) {
		int length=hexstr.length();
		if(length%2!=0){
			throw new RuntimeException("Hex  bit string length must be even");
		}
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) ((parse(c0) << 4) | parse(c1));
		}
		return b;
	}
	  
	  private static int parse(char c) {
		  if (c >= 'a')
		   return (c - 'a' + 10) & 0x0f;
		  if (c >= 'A')
		   return (c - 'A' + 10) & 0x0f;
		  return (c - '0') & 0x0f;
	  }

 

 注意:当十六进制位串转化为字节数组时,十六进制位串的位数必须是偶数的,因为两个十六进制位串对应一个字节

 

你可能感兴趣的:(java)