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?
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With