把十六进制的位串转化为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;
	  }

 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值