Simple operations with TCP/IP Header bits

870 views Asked by At

I have two doubts related to operations with bits:

The first one is the >> operator. As far as I have read, this operator does this

0001 0000 >> 4 --> 0000 0001 or this 1111 0001, not sure if it fills with 1s or 0s

So I have this code:

version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF

Let's say IP Version is 4: 0100 and IHL is 5: 0101

If I do the version = version_ihl >> 4, the result would be

0100 0101 ---> 0000 0100 in case the operator >> doesn't fill with 1, which I have read it actually does, so instead of IP Version = 4 would be 1111 0100 which is not 4 at all.

The second thing is this line, how to calculate ihl with ihl = version_ihl & 0xF

The final result is 5, so 0000 0101 and as far as I know, that operator does a mask of all 1s, so 0100 0101 would remain the same. So the two questions are :

1.How do you obtain from 0100 0101 with >> 4 operation the result 0000 0100 if >> is supposed to fill with 1s¿?

2.How do you obtain from 0100 0101 the result 0000 0101 with the & 0xF mask¿?

The code I posted worked perfectly right, so the solution is there, I just want to know why it works like that. Thank you in advance, hope someone could through some light on this.

1

There are 1 answers

2
Kevin On BEST ANSWER
  1. The >> operator does not "fill" anything with anything. Integers in Python behave as though they have an infinite number of leading zeros (nonnegative integers) or ones (negative integers). Right-shifting simply drops the n least significant bits.
  2. 0xF is the same as 0b1111, which in turn is the same as 0b00001111. You are only masking the least significant nybble with ones.

Since you asked for more detail:

  1. You started with 0100 0101 and right-shifted by four. That's exactly equivalent to starting with 0000 0100 0101 and right-shifting by four, which gives you 0000 0100. That, in turn, is the same as 0100.
  2. You started with 0100 0101 and masked with 0xF. 0xF is just 1111, which is the same as 0000 1111. So you get 0000 0101, or just 0101