바보 코딩 사례를 공유 할 수 있습니다.
원래, 나는 바이트 배열에 바이트 진수 문자열을 넣어, 엉덩이 계약에 있었다
프로토콜 명령이 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 진수 바이트 배열에 임의의 문자열 (두 바이트로 문자열 당 바이트)
/**
* 将随机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");
테스트 결과 :