ランダムな16進数の文字列のJavaバイト配列の転送

愚かなコーディングケースを共有します。

もともと、私は、バイト配列にバイトの16進数の文字列を入れて、お尻の一致しました

プロトコルコマンドは、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;		
	}

次のようにコンソールを印刷:

 

人々はちょうどハハ、ない通常兄を行います

 

更新:

 進バイト配列(バイトとして文字列につき2バイト)にランダムな文字列

/**
     * 将随机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 ビュー50000 +

おすすめ

転載: blog.csdn.net/qq_43560721/article/details/102625298