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

java中hex转byte问题

2015-08-23 20:51 387 查看

今天在写个程序,把服务端16进制串再转成base64编码,传给体重硬件,但是碰到个问题,如下:

 

年龄、性别、身高,这三个数值需要用10进制转16进制,OK,我们用了Integer.toHexString(age)进行处理,这里转出来的是16进制,并且把这三个值拼凑成一个字符串。

 

那么问题来了,base64位是需要用byte来转的,我们一不小心,直接就使用jdk中字符串.getBytes()方法,完全把16进制字符串的意思改变了,转出来的码也不一样。最后上网才知道hex串需要按照字节一个个去转。

 

public static  byte[] hex2Bytes( String hex ) {
if( isEmpty(hex) || hex.length() %2> 0 ) {
log.error("hex2Bytes: invalid HEX string:" + hex );
return null;
}
int len = hex.length() / 2;
byte[] ret = new byte[ len ];
int k = 0;
for (int i = 0; i < len; i++) {
int c = hex.charAt(k++);
if( c>='0'&& c<='9' )
c = c-'0';
else if( c>='a'&& c<='f' )
c = c-'a'+ 10;
else if( c>='A'&& c<='F' )
c = c-'A'+ 10;
else {
log.error("hex2Bytes: invalid HEX string:" + hex );
return null;
}
ret[i]= (byte)(c<<4);
c = hex.charAt(k++);
if( c>='0'&& c<='9' )
c = c-'0';
else if( c>='a'&& c<='f' )
c = c-'a'+ 10;
else if( c>='A'&& c<='F' )
c = c-'A'+ 10;
else {
log.error("hex2Bytes: invalid HEX string:" + hex );
return null;
}
ret[i]+= (byte)c;
}
return ret;
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: