0

I need to "AND" a IP address with its subnet mask. IP address is a hexadecimal number and the subnet mask is a number between 0 - 32 (not 0).

4a21bd6e/25

Can I use the bellow code to "AND" these two variables to obtain most significant 25 bits of the IP address?

uint32_t IP = 4a21bd6e;
uint8_t netmask = 25;
int mask = 0x80000000;
uint32_t results = IP & (mask  >> (netmask - 1));
kiki
  • 37
  • 1
  • 5
  • 1
    did you try it? what did you expect and what was the result? – mch Oct 12 '14 at 16:57
  • I edit two last line code, it works well but I want to be sure. – kiki Oct 12 '14 at 17:03
  • an IPv4 address is a 4 byte value and an IPv4 subnet mask is also a 4 byte value. Please explain what it is you are attempting to do with the shifting. if you want the most significant 25 bits then just use a hex value for that value. – Richard Chambers Oct 12 '14 at 17:05
  • We can show subnet mask by a number between 0 to 32. If we want to obtain most significant netmask bits we have to "AND" the IP address with somthing like 0xff000000 (8 bits netmask) but if we have 8 instead of 0xff000000 how can we perform this ? – kiki Oct 12 '14 at 17:13
  • @RichardChambers What's a "hex"-value? Please more specific/accurate. – alk Oct 12 '14 at 17:14
  • Reading this http://stackoverflow.com/a/4009922/694576 might help. – alk Oct 12 '14 at 17:18
  • The hex value is : uint32_t IP = 0x4a21bd6e;. I forgot the "0x".. – kiki Oct 12 '14 at 17:25

2 Answers2

1

The answer is maybe - if your compiler/processor choice does:

Arithmetic bit-shift on a signed integer

Community
  • 1
  • 1
Rich
  • 640
  • 5
  • 12
0

Why not use uint32_t like you used for IP? You are assuming int is 4 bytes but that is not always the case. Generally it is better to use standard types as it is more portable and not architecture specific.

oren zvi
  • 114
  • 1
  • 4