Vid - 10 months ago 58

C Question

I there any way to check that 32 bit netmask is valid or not using bitwise operator?

I have to check from msb side that '1' are in continuous stream or not.

eg 11111111.0.0.0 (255.0.0.0)is valid

but 11111101.0.0.0 (253.0.0.0) is not.

Answer

First thing to do is to check for the netmask being non zero (a nasty edge case). Given this is ok, you need to take the bitwise inverse.

```
uint32_t y = ~x;
```

Then add one

```
uint32_t z = y + 1;
```

Then if `x`

was a proper netmask, there will be at most 1 bit set in this.

To test that, simply and `z`

with `z - 1`

, which happens to be `y`

. The result will be zero if all is OK, non zero otherwise.

```
valid = (z & y) == 0;
```

Source (Stackoverflow)