views:

466

answers:

4

Hey guys!

I've been looking at bitwise operations as a way of speeding things up in critical areas. But most of what I find are just low level explanations.

Would anyone be so kind as to briefly explain what practical situations i may find myself needing bitwise operations? Or perhaps a link to a good tutorial?

Thanks!

+6  A: 

Is it what you want ?

http://blog.code-head.com/how-to-write-a-permission-system-using-bits-and-bitwise-operations-in-php

Cédric Boivin
Yes, that helps. Thank you very much
Jeff
+1 Interesting.
+3  A: 

This is my answer to this question,

http://stackoverflow.com/questions/1251854/php-ip-to-network-translation

This snippet is from real production code. It has bitwise-and and bit shifting. I think this is pretty hard to do without bitwise operations.

<?php

function to_netmask($ip, $prefix) {
    $mask = $prefix==0?0:0xffffffff << (32 - $prefix);
    return long2ip(ip2long($ip) & $mask);
}

?>
ZZ Coder
Wouldn't 0xffffffff << (32 - $prefix) be 0 if prefix is 0? Or is the case there for speed reasons (prefix 0 gets used a lot).
Toon Van Acker
This code is ported from C implementation. We had some problem with 0xffffffff << 32, which may result a non-zero value on some platforms.
ZZ Coder
Ahh, interesting pitfall! I'll have to keep that in mind
Toon Van Acker
A: 

I doubt that you'll get performance boost in PHP. It's a good practice to use them since it takes less space when you store (true/false) settings.

In C/C++, you could use them to get a speed boost when shifting left or right..

ie: x << 1 // equal x=x*2 x << 2 // equal x=x*4 x << 3 // equal x=x*8

  x >> 1   // equal  x=x/2

since binary shifting is faster than doing a division or multiplication, it was often use for that. The caveat is that it only works with unsigned integer (no float)

using bit shifting for speed improvement is not recommended anymore since compilers are really more aggressive regarding optimizations. If you add code hints the compiler will choose the best method.

Bitwise operators are really practical. A good example is indicated in the first answer

A: 

Might be a bit late, but I've provided an example here

http://13.7billionyearslater.net/2010/07/16/using-bit-operations-in-php-an-example/

neilc