当前位置: 代码迷 >> Web前端 >> 字符串跟16进制互转
  详细解决方案

字符串跟16进制互转

热度:108   发布时间:2012-08-26 16:48:05.0
字符串和16进制互转
public class TestHex {

	public static String toHexString(byte[] value,int start,int len) { 
	    if (value == null ) return null;
	    
		String newString = ""; 
		for (int i = start; i < start + len; i++) { 
		byte b = value[i]; 
		String str = Integer.toHexString(b); 
		if (str.length() > 2) { 
		str = str.substring(str.length() - 2); 
		} 
		if (str.length() < 2) { 
		str = "0" + str; 
		} 
		newString += str + " "; 
		} 
		return newString.toUpperCase(); 
	  
	}
	public static byte[] hexToBytes(String hexString) {
		
        if (hexString == null) return null;
        hexString = hexString.replaceAll(" ", "");
        byte[] bytes = new byte[hexString.length()/2];
        for (int i=0; i<bytes.length; i++) {
            bytes[i] = (byte)Integer.parseInt(hexString.substring(i*2, i*2+2), 16);            
        }
        return bytes;
    }
	
	public static byte[] hexToBytes1(String hexString) {
		String[] temp = hexString.split(" ");
		byte[] bytes = new byte[temp.length];
		for(int i=0;i<temp.length;i++){
			bytes[i] = (byte)Integer.parseInt(temp[i], 16);
		}
        return bytes;
    }
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String temp = "我测试";
		byte[] temp1 = temp.getBytes();
		String a = toHexString(temp1,0,temp1.length);
		System.out.println(a);
		byte[] temp2 = hexToBytes(a);
		String b = new String(temp2);
		System.out.println(b);
		byte[] temp3 = hexToBytes1(a);
		String c = new String(temp3);
		System.out.println(c);
		
	}

}


结果:

E6 88 91 E6 B5 8B E8 AF 95
我测试
我测试
  相关解决方案