newbie12345
newbie12345

Reputation: 29

left/right bitwise shifts - why do we shift by byte length

I have been reading this blog about bit manipulation in networking packages. I have this code and I am seeing that its reading in an integer which is typically 4 bytes long (32 bits)

public int readInt() {
    return (pData[caret++] & 0xff) << 24 | (pData[caret++] & 0xff) << 16
            | (pData[caret++] & 0xff) << 8 | pData[caret++] & 0xff;
}

Why are we moving by 8, 16 and 24 when reading in an integer value? What is the goal and what does it achieve?

Upvotes: 0

Views: 210

Answers (1)

Darkman
Darkman

Reputation: 2981

That is because pData is a byte array. What readInt() does is pack 4 bytes into an integer then return the result. Because an integer is 4 bytes, by ((value & 0xFF) << 24) will set for the 1'st slot, ((value & 0xFF) << 16) for the 2'nd slot, ((value & 0xFF) << 8) for the 3'rd slot and (value & 0xFF) for the last slot. And to merge these four values into one (that in this case is an integer), bitwise OR ( |) must be performed between each value. If pData is indeed an integer array, thats probably because it wants to use unsigned integers (0 - 255). So what readInt() does is pack 8 LSB (least significant bits) for each int (up to 4 integers) into an integer then return the result.

Upvotes: 1

Related Questions