代码之家  ›  专栏  ›  技术社区  ›  Elzo Valugi

PHP中的位操作?

  •  28
  • Elzo Valugi  · 技术社区  · 15 年前

    你能给我举个用法的例子吗?

    2 回复  |  直到 9 年前
        1
  •  47
  •   Community CDub    8 年前

    您可以将其用于位掩码来对事物的组合进行编码。基本上,它通过赋予每一点意义来工作,所以如果你有 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    |
    

        2
  •  18
  •   Peter Mortensen icecrime    9 年前

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

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

    等等

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