Search code examples
cipv4

IP Address left shift representation


I found the following in some old and bad documented C code:

#define addr (((((147 << 8) | 87) << 8) | 117) << 8) | 107

What is it? Well I know it's an IP address - and shifting 8 bits to the left makes some sense too. But can anyone explain this to me as a whole? What is happening there?

Thank you!


Solution

  • The code

    (((((147 << 8) | 87) << 8) | 117) << 8) | 107
    

    generates 4 bytes containing the IP 147.87.117.107. The first step is the innermost bracket:

    147<<8
    147 = 1001 0011
    1001 0011 << 8 = 1001 0011 0000 0000
    

    The second byte 87 is inserted by bitwise-or operation on (147<<8). As you can see, the 8 bits on the right are all 0 (due to <<8), so the bitwise-or operation just inserts the 8 bits from 87:

    1001 0011 0000 0000  (147<<8)
    0000 0000 0101 0111  (87)
    -------------------  bitwise-or
    1001 0011 0101 0111  (147<<8)|87
    

    The same is done with rest so you have 4 bytes at the end saved into a single 32-bit integer.