Android与单片机通信常用数据转换方法总结
Android与单片机通信常用数据转换方法
1. 将GB2312转化为中文,如BAFAC2DCB2B7→胡萝卜,两个字节合成一个文字
publicstaticStringstringToGbk(Stringstring)throwsException{
byte[]bytes=newbyte[string.length()/2];
for(intj=0;j<bytes.length;j++){
bytehigh=Byte.parseByte(string.substring(j*2,j*2+1),16);
bytelow=Byte.parseByte(string.substring(j*2+1,j*2+2),
16);
bytes[j]=(byte)(high<<4|low);
}
Stringresult=newString(bytes,"GBK");
returnresult;
}
2.将中文转化为GB2312,并且结果以byte[]形式返回,如胡萝卜→newbyte[]{BA FAC2DCB2B7},一个字被分为两个字节
publicstaticbyte[]gbkToString(Stringstr)throwsException{
returnnewString(str.getBytes("GBK"),"gb2312").getBytes("gb2312");
}
3.将十六进制的byte[]原封不动的转化为string,如byte[]{0x7e,0x80,0x11,0x20}→7e801120,可用于log打印
publicstaticStringbytesToHexString(byte[]src){
StringBuilderstringBuilder=newStringBuilder("");
if(src==null||src.length<=0){
returnnull;
}
for(inti=0;i<src.length;i++){
intv=src[i]&0xFF;
Stringhv=Integer.toHexString(v);
if(hv.length()<2){
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
returnstringBuilder.toString();
}
4.将十六进制的byte[]原封不动的转化为string,并且每个byte之间用空格分开,如byte[]{0x7e,0x80,0x11,0x20}→7e801120,,可用于log打印
publicstaticStringBuilderbyte2HexStr(byte[]data){
if(data!=null&&data.length>0){
StringBuilderstringBuilder=newStringBuilder(data.length);
for(bytebyteChar:data){
stringBuilder.append(String.format("%02X",byteChar));
}
returnstringBuilder;
}
returnnull;
}
5.将byte[]数组转化为8、10、16等各种进制,例如byte[0x11,0x20]→4384,约等于1120(16进制)→4384,radix代表进制
publicstaticStringbytesToAllHex(byte[]bytes,intradix){
returnnewBigInteger(1,bytes).toString(radix);//这里的1代表正数
}
6.将String的十六进制原封不动转化为byte的十六进制,例如7e20→newbyte[]{0x7e,x20}
publicstaticbyte[]HexString2Bytes(Stringsrc){
byte[]ret=newbyte[src.length()/2];
byte[]tmp=src.getBytes();
for(inti=0;i<tmp.length/2;i++){
ret[i]=uniteBytes(tmp[i*2],tmp[i*2+1]);
}
returnret;
}
publicstaticbyteuniteBytes(bytesrc0,bytesrc1){
byte_b0=Byte.decode("0x"+newString(newbyte[]{src0}))
.byteValue();
_b0=(byte)(_b0<<4);
byte_b1=Byte.decode("0x"+newString(newbyte[]{src1}))
.byteValue();
byteret=(byte)(_b0^_b1);
returnret;
}
以上就是对Android与单片机通信的资料整理,后续继续补充相关资料谢谢大家对本站的支持!