我有一個字節數組,其中包含6個字節的最後2代表端口號,同時尋找一個路兩將這些最後字節端口號我也碰到過這個片段中,片段澄清字節數組端口號
int port = 0;
port |= peerList[i+4] & 0xFF;
port <<= 8;
port |= peerList[i+5] & 0xFF;
它的工作原理,但我需要澄清一下它是如何工作的?
我有一個字節數組,其中包含6個字節的最後2代表端口號,同時尋找一個路兩將這些最後字節端口號我也碰到過這個片段中,片段澄清字節數組端口號
int port = 0;
port |= peerList[i+4] & 0xFF;
port <<= 8;
port |= peerList[i+5] & 0xFF;
它的工作原理,但我需要澄清一下它是如何工作的?
======================= | byte 5 | byte 6 | |----------|----------| | 01010101 | 01010101 | =======================
基本上,它以字節#5,移爲8位,從而導致0101010100000000
左側,然後使用按位或操作者把字節6中的零的位置。
代碼只是從數組中取出最後2個字節,並將它們用作大端數字。
通常在網絡數據包中,端口號以big-endian傳輸(意思是低地址的字節更重要)。
該代碼需要字節數i + 4,並將其用作MSB和字節i + 5作爲端口號的LSB。
int port = 0; // Start with zero
port |= peerList[i+4] & 0xFF; // Assign first byte to port using bitwise or.
port <<= 8; // Shift the bits left by 8 (so the byte from before is on the correct position)
port |= peerList[i+5] & 0xFF; // Assign the second, LSB, byte to port.
如果原始字節的頂端位爲1,則需要&0xFF來保持結果int爲負。 – 2009-06-20 11:47:02