您的位置:首页 > 编程语言 > Java开发

java后台与硬件对接经验

2016-01-13 14:27 405 查看
8421BCD编码,用于存储手机号码,每2位手机号码存储于一个byte中,详细转换如下:

  比如手机号码 13129911472 ,13拆开为1和3,1对应2进制为 0000 0001,3对应2进制为 0000 0011,合并只有为 0001 0011,对应byte为 19,对应16进制为 0x13

byte转10进制:

byte b=19;
int a=b&0xFF; //byte转int 此时 a=19
byte b=-103;
int a=b&0xFF; //byte转int 此时a=153


10进制转16进制:

int a=19;
String hex=Integer.toHexString(a); //10进制转16进制,此时hex =13


byte数组转16进制:

public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b
& 0XFF));
if (stmp.length() == 1)//小于16会补0
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}


16进制字符串转10进制:

String str="AC";
int num=Integer.parseInt(str,16);//此时 num 为172
byte b=(byte)num; //此时byte 为 -84


16进制字符串转byte数组

public static byte[] hex2byte(String content) {
byte[] mtemp=new byte[content.length()/2];//初始化byte数组,长度为lenth/2,每2个表示一个byte
int j=0;
for (int n=0; n<content.length(); n=n+2) {//每次增加2
String sTemp=content.substring(n,n+2);//截取每2个
//0xca-256=-54
mtemp[j]=(byte)Integer.parseInt(sTemp, 16);//先转成10进制int,然后再转成byte
j++;
}
return mtemp;
}


字符串获取特定编码字节数组:

public static byte[] getBytesArray(String str,String changeToCharset)
throws UnsupportedEncodingException {
return str.getBytes(changeToCharset);
}


对字节数组通过特定编码获取字符串:

public static String bytesToString(byte[] bs,String changeToCharset)
throws UnsupportedEncodingException {
return new String(bs,changeToCharset);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: