Reputation: 85
I'd like to convert a prefix like /24 to 255.255.255.0 using bitwise operations.
I have tried using unsigned int like so:
unsigned int mask = -(1 << 32 - prefix);
I am thinking of creating a while loop that adds 1 to the correct place and then decrements to 0.
All help would be appreciated!
Upvotes: 1
Views: 9588
Reputation: 62048
Use
unsigned long mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF;
printf("%lu.%lu.%lu.%lu\n", mask >> 24, (mask >> 16) & 0xFF, (mask >> 8) & 0xFF, mask & 0xFF);
Upvotes: 4
Reputation: 10655
Have you tried?
#include <stdint.h>
uint32_t mask = (-1) << (32 - prefix);
once -1 is 0xFFFFFFFF in 2-complement notation, it does the work
Upvotes: 1