Snippet Clarification byte array to port number
Question
I have a byte array that contains 6 bytes last 2 represents the port number while searching for a way two convert these last to bytes to a port number i have come across this snippet,
int port = 0;
port |= peerList[i+4] & 0xFF;
port <<= 8;
port |= peerList[i+5] & 0xFF;
it works but i need some clarification as to how it works?
Solution
======================= | byte 5 | byte 6 | |----------|----------| | 01010101 | 01010101 | =======================
Basically, it takes byte #5, shift is 8 bits to the left resulting in 0101010100000000
and then uses the bitwise or operator to put the byte 6 in the place of zeros.
OTHER TIPS
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.
The code simply takes the last 2 bytes from the array and uses them as a big-endian number.
Usually in network packets the port number is transferred in big-endian (meaning the byte with the lower address is more significant).
The code takes byte number i+4 and uses it as the MSB and byte i+5 as the LSB of the port number.