开发者

Bitwise operations in PHP?

I understand that bitwise operations are necessary for much low-level programming, such a开发者_JAVA百科s writing device drivers, low-level graphics, communications protocol packet assembly and decoding. I have been doing PHP for several years now, and I have seen bitwise operations very rarely in PHP projects.

Can you give me examples of usage?


You could use it for bitmasks to encode combinations of things. Basically, it works by giving each bit a meaning, so if you have 00000000, each bit represents something, in addition to being a single decimal number as well. Let's say I have some preferences for users I want to store, but my database is very limited in terms of storage. I could simply store the decimal number and derive from this, which preferences are selected, e.g. 9 is 2^3 + 2^0 is 00001001, so the user has preference 1 and preference 4.

 00000000 Meaning       Bin Dec    | Examples
 │││││││└ Preference 1  2^0   1    | Pref 1+2   is Dec   3 is 00000011
 ││││││└─ Preference 2  2^1   2    | Pref 1+8   is Dec 129 is 10000001
 │││││└── Preference 3  2^2   4    | Pref 3,4+6 is Dec  44 is 00101100
 ││││└─── Preference 4  2^3   8    | all Prefs  is Dec 255 is 11111111
 │││└──── Preference 5  2^4  16    |
 ││└───── Preference 6  2^5  32    | etc ...
 │└────── Preference 7  2^6  64    |
 └─────── Preference 8  2^7 128    |

Further reading

  • http://www.weberdev.com/get_example-3809.html
  • http://stu.mp/2004/06/a-quick-bitmask-howto-for-programmers.html
  • Why should I use bitwise/bitmask in PHP?
  • http://en.wikipedia.org/wiki/Mask_%28computing%29


Bitwise operations are extremely useful in credentials information. For example:

function is_moderator($credentials)
{ return $credentials & 4; }

function is_admin($credentials)
{ return $credentials & 8; }

and so on...

This way, we can keep a simple integer in one database column to have all credentials in the system.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜