Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operations in PHP?

I understand that bitwise operations are necessary for much low-level programming, such as 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?

like image 472
Elzo Valugi Avatar asked Jan 25 '10 11:01

Elzo Valugi


People also ask

What are bitwise operators in PHP?

The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then calculation is performed on the operands. The mathematical operations such as addition , subtraction , multiplication etc.

What is Bitwise operation used for?

Examples of uses of bitwise operations include encryption, compression, graphics, communications over ports/sockets, embedded systems programming and finite state machines. A bitwise operator works with the binary representation of a number rather than that number's value.


2 Answers

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
like image 143
Gordon Avatar answered Oct 02 '22 22:10

Gordon


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.

like image 33
TomaszSobczak Avatar answered Oct 02 '22 21:10

TomaszSobczak