java随机十六进制字符串转byte数组

分享一个愚蠢的编码案例。

本来我是在对接协议,要将16进制字符串转为byte放进byte数组,

因为协议命令都是前加0x的,我就想当然开始下手了。

刚开始是这样写的。

是不是很愚蠢呢?不过毕竟是第一次写,我就去问度娘,请教大佬。

然后是这样的。

有点怀疑我是不是没有跟大佬说清楚我要请教的东西,但是自己又不确定,就去找方法验证,结果是这样的。

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;		
	}

控制台打印如下:

人家大佬就是不一般,哈哈

升级版:

 将随机16进制字符串转为byte数组(每两个字节字符串作为一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;
    }

测试:

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

测试结果:

发布了141 篇原创文章 · 获赞 33 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43560721/article/details/102625298