PHP 中的按位操作?

2022-08-30 15:10:34

我知道按位操作对于许多低级编程是必要的,例如编写设备驱动程序,低级图形,通信协议数据包组装和解码。我已经做了几年PHP了,在PHP项目中我很少看到按位操作。

你能给我一些用法的例子吗?


答案 1

您可以将它用于位掩码来编码事物的组合。基本上,它的工作原理是赋予每个位一个含义,所以如果你有,每个位代表一些东西,除了是一个十进制数。假设我对要存储的用户有一些首选项,但我的数据库在存储方面非常有限。我可以简单地存储十进制数并从中派生,选择哪些首选项,例如 是 + is ,因此用户具有首选项 1 和首选项 4。0000000092^32^000001001

 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    |

进一步阅读


答案 2

按位操作在凭据信息中非常有用。例如:

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

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

等等...

这样,我们可以在一个数据库列中保留一个简单的整数,以便在系统中获得所有凭据。


推荐