16進制字符串轉字節數組

直接上代碼:java

public static void main(String[] args) {
		 String str="23555555550b01010000D002002A";
		 byte[] d =hexStringToBytes(str);
		 printHexString(d);
	}
	/** 
	 * 16進制字符串轉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;  
	}  
	/** 
	 * 16進制字符byte 
	 * @param c char 
	 * @return byte 
	 */  
	 private static byte charToByte(char c) {  
	    return (byte) "0123456789ABCDEF".indexOf(c);  
	} 

	//將指定byte數組以16進制的形式打印到控制檯  
	 public static void printHexString( byte[] b) {    
	    for (int i = 0; i < b.length; i++) {   
	      String hex = Integer.toHexString(b[i] & 0xFF);   
	      if (hex.length() == 1) {   
	        hex = '0' + hex;   
	      }   
	      System.out.print(hex.toUpperCase() );   
	    }   
	   
	 }

效果:數組

相關文章
相關標籤/搜索