Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

bit manipulation - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...