random hexadecimal string java byte array transfer

Share a stupid coding case.

Originally, I was in the butt agreement, to put byte hexadecimal string to a byte array,

Because the protocol commands are preceded by 0x, I take it for granted began to bite.

 

The beginning is written like this.

 

 

Is not it foolish? But, after all, is the first time to write, I had to ask of your mother, ask big brother.

Then is this.

 

I is not no little doubt tell Gangster clear what I want to ask, but are not sure themselves, went to method validation, the result is this.

public static void main(String[] args) {
		/**
		 * 8-0-83-f4-48-11-fe-9d
		 */
		String sn = "1148f483";		
		String code3 =sn.substring(0, 2);
		String code2 =sn.substring(2, 4);
		String code1 =sn.substring(4, 6);
		String code0 =sn.substring(6, 8);
		System.out.println("11: "+getCode(code3)+"-----48: "+getCode(code2)+"------f4: "+getCode(code1)+"--------83: "+getCode(code0));
		//byte[] code = {0x08,0x00,(byte) 0x83,(byte) 0xf4,0x48,0x11,(byte) 0xFE,(byte) 0x9D};
		byte[] code = {0x08,0x00,(byte) getCode(code0),(byte) getCode(code1),(byte) getCode(code2),(byte) getCode(code3),(byte) 0xFE,(byte) 0x9D};
		if(Integer.toHexString(code[3]&0xff).equals("f4")){
			System.out.println("success");
		}else{
			System.out.println("fail");
		}
		StringBuilder sb  = new StringBuilder();
		for(int i=0;i<code.length;i++){
			if(i==0){
				//java.lang.Integer.toHexString() 方法的参数是int(32位)类型,如果输入一个byte(8位)类型的数字,这个
				//方法会把这个数字的高24为也看作有效位,这就必然导致错误,使用& 0XFF操作,可以把高24位置0以避免这样错误的发生。
				sb.append(Integer.toHexString(code[i]&0xff)+"");
			}else if(i>0){
				sb.append("-"+Integer.toHexString(code[i]&0xff));
			}
		}
		System.out.println("sb......"+sb);
	}
	/**
	 * 将截取16进制字符串转换为byte类型
	 * @param str
	 * @return
	 */
	public static int getCode(String str){ 
		int h = Integer.parseInt(str.substring(0,1),16);
		int l = Integer.parseInt(str.substring(1,2),16);
//		byte H = (byte) h;	
//		byte L = (byte) l;	
//		int s = H<<4 | L;
		byte s = (byte) (((byte)h<<4) + (byte) l);		
		return s;		
	}

Print Console as follows:

 

People just do not usually big brother, ha ha

 

Upgraded version:

 The random string to a hexadecimal byte array (two bytes per character string as a byte)

/**
     * 将随机16进制字符串转为byte数组(每两个字节字符串作为一byte)
     * @param ieee
     * @return
     */
    public static byte[] hexStrChangeByte(String hexStr){
    	byte[] codeByte = new byte[hexStr.length()/2];
		for(int i=0;i<codeByte.length;i++){			
			String code = hexStr.substring(2*i, 2*i+2);
			codeByte[i] = (byte) getCode(code);						
		}
		System.out.println(Arrays.toString(codeByte));
        return codeByte;
    }

 

test:

hexStrChangeByte("1148f483");
		hexStrChangeByte("3132302e37382e3134342e3137343a38353939");

Test Results:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Published 141 original articles · won praise 33 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_43560721/article/details/102625298