Operator Bitwise Right

Asked

Viewed 63 times

0

Hello

Conducting some studies on PHP I came across bitwise and until then all its operations has not been anything difficult, just the one of the right shift

An exmeplo I took and I still don’t understand was this:

print(4>>6); //onde o resultado final é igual a zero

And looking at a book I realized the following calculation for this expression:

4/2^6
2^6 = 2*2*2*2*2*2=64
64/4 = 0,06 

That in the case would be equal to zero, which is the result that php returns me, although I think it should give 16. Could someone explain this logic to me?

  • The language is different, but the functioning is the same

2 answers

2

Dividend is 4 and the divisor is 64.

In the expression is reversed.

The right then is 4 / 64, whose result is 0.0625

  • thanks for the help Daniel

2


See the 4 in base 2:

00000100

Now let’s move it once to the right ( 4 >> 1 ):

00000010

If we moved twice ( 4 >> 2 ):

00000001

Moving 6 houses, the bit was "gone", so the result 0.

Look at the left shift, I’ll take the number 6 as an example, and move twice:

00000110 (6)

00011000 (6<<2 = 24)

In short:

  • when you shift to right, is divided by 2 at every step.

  • when it moves to left, is multiplying by 2 at every step.


See more details here:

How the bit offset in C/C works++?

  • Thanks for the help Bacco, the example I caught tbm was wrong as Daniel reported, and sorry for the duplicity in the question

  • 1

    @tkmattos close by duplicate is just to concentrate the information in one place, rest assured that is not "penalty".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.