今天在寫個程序,把服務端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;
}