- 相關(guān)推薦
Java byte[]轉(zhuǎn)int如何實(shí)現(xiàn)
函數(shù)需要:
傳入一個(gè)一維byte數(shù)組, 比如{255,255} 轉(zhuǎn)換為int 為65535,相當(dāng)于16進(jìn)制FFFFH,以此類推,當(dāng)傳入為{255,1}時(shí),返回int為511,相當(dāng)于1FFH.
基本上是用在協(xié)議解析上,當(dāng)有兩個(gè)byte表示長(zhǎng)度協(xié)議時(shí),用此函數(shù)可以得到協(xié)議的長(zhǎng)度。
代碼如下:
Java代碼
public static int bytesToInt(byte[] intByte) {
int fromByte = 0;
for (int i = 0; i < 2; i++)
{
int n = (intByte[i] < 0 ? (int)intByte[i] + 256 : (int)intByte[i]) << (8 * i);
System.out.println(n);
fromByte += n;
}
return fromByte;
}
而網(wǎng)上找的一些其他代碼就不頂用不知道為什么,如:
Java代碼
public static int bytesToInt(byte[] bytes) {
int num = bytes[0] & 0xFF;
num |= ((bytes[1] << 8) & 0xFF00);
return num;
}
【Java byte[]轉(zhuǎn)int如何實(shí)現(xiàn)】相關(guān)文章:
Java如何實(shí)現(xiàn)點(diǎn)的在線添加08-31
關(guān)于JAVA實(shí)現(xiàn)httpClient的實(shí)例11-05
使用JavaScript實(shí)現(xiàn)Java的List功能08-09
java實(shí)現(xiàn)web服務(wù)器的方法09-26
如何傳輸Java對(duì)象07-29
如何實(shí)現(xiàn)柔韌素質(zhì)的訓(xùn)練10-05
如何實(shí)現(xiàn)員工的有效激勵(lì)07-23