最近一個搞 android 開發(fā)的同學(xué)在使用字節(jié)流通信時遇到了byte[]轉(zhuǎn)int時問題,在此記錄一下,方便日后查閱.
java下沒有無符號的整形(unsigned char,unsigned short,unsigned int,unsigned long), 字節(jié)流通信時往往需要把byte[]轉(zhuǎn)成對應(yīng)的整形,符號位處理不當(dāng)會導(dǎo)致數(shù)據(jù)解析失敗.
不同整形對應(yīng)的字節(jié)長度不一, 可以統(tǒng)一為long來處理.
byte占一個字節(jié),如果不做處理直接付給int或long類型的變量,當(dāng)高位為1時會導(dǎo)致得到不正確的值(負(fù)數(shù)), 如果與0xff(或者0xffL)做位與就可以保證得到byte本身的值.
public class Main {
public static void main(String[] args) {
byte[] bs1 = new byte[1];
bs1[0] = (byte) 0xf2;
byte[] bs2 = new byte[2];
bs2[0] = (byte) 0xa2;
bs2[1] = 0x32;
byte[] bs3 = new byte[4];
bs3[0] = (byte) 0xe2;
bs3[1] = 0x12;
bs3[2] = 0x22;
bs3[3] = 0x52;
byte[] bs4 = new byte[8];
bs4[0] = (byte) 0x82;
bs4[1] = 0x12;
bs4[2] = 0x22;
bs4[3] = 0x32;
bs4[4] = 0x42;
bs4[5] = 0x52;
bs4[6] = 0x62;
bs4[7] = 0x72;
try {
System.out.printf("value1: %016x\n", bytes2long(bs1));
System.out.printf("value2: %016x\n", bytes2long(bs2));
System.out.printf("value3: %016x\n", bytes2long(bs3));
System.out.printf("value4: %016x\n", bytes2long(bs4));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* (non-Java-doc)
* @see java.lang.Object#Object()
*/
public Main() {
super();
}
static long bytes2long(byte[] bs) throws Exception {
int bytes = bs.length;
if(bytes > 1) {
if((bytes % 2) != 0 || bytes > 8) {
throw new Exception("not support");
}}
switch(bytes) {
case 0:
return 0;
case 1:
return (long)((bs[0] & 0xff));
case 2:
return (long)((bs[0] & 0xff) <<8 | (bs[1] & 0xff));
case 4:
return (long)((bs[0] & 0xffL) <<24 | (bs[1] & 0xffL) << 16 | (bs[2] & 0xffL) <<8 | (bs[3] & 0xffL));
case 8:
return (long)((bs[0] & 0xffL) <<56 | (bs[1] & 0xffL) << 48 | (bs[2] & 0xffL) <<40 | (bs[3] & 0xffL)<<32 |
(bs[4] & 0xffL) <<24 | (bs[5] & 0xffL) << 16 | (bs[6] & 0xffL) <<8 | (bs[7] & 0xffL));
default:
throw new Exception("not support");
}
//return 0;
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者