Search code examples
network-programmingbit-manipulation

What's the best way to convert from network bitcount to netmask?


For example, if I have a network spec like 172.20.10.0/24, "24" is the bitcount. What's the best way to convert that to a netmask like 0xffffff00 ?


Solution

  • Why waste time with subtraction or ternary statements?

    int suffix = 24;
    int mask = 0xffffffff ^ 0xffffffff >> suffix;
    

    If you know your integer is exactly 32 bits long then you only need to type 0xffffffff once.

    int32_t mask = ~(0xffffffff >> suffix);
    

    Both compile to the exact same assembly code.