Elz*_*ugi 29 php bit-manipulation
我知道按位操作对于许多低级编程是必要的,例如编写设备驱动程序,低级图形,通信协议数据包组装和解码.我已经做了几年PHP,我在PHP项目中很少见到按位操作.
你能告诉我一些使用方法吗?
Gor*_*don 47
您可以将它用于位掩码来编码事物的组合.基本上,它通过赋予每个位一个含义来工作,所以如果你有00000000
,每个位代表一些东西,除了也是一个十进制数.假设我对要存储的用户有一些偏好,但我的数据库在存储方面非常有限.我可以简单地存储十进制数并从中导出,选择哪些偏好,例如9
是2^3
+ 2^0
是00001001
,因此用户具有偏好1和偏好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 |
Run Code Online (Sandbox Code Playgroud)
进一步阅读
sbc*_*czk 18
按位运算在凭证信息中非常有用.例如:
function is_moderator($credentials)
{ return $credentials & 4; }
function is_admin($credentials)
{ return $credentials & 8; }
Run Code Online (Sandbox Code Playgroud)
等等...
这样,我们可以在一个数据库列中保留一个简单的整数,以获得系统中的所有凭据.