C & PHP: Storing settings in an integer using bitwise operators?

后端 未结 3 885
醉梦人生
醉梦人生 2020-12-14 09:57

I\'m not familiar with bitwise operators, but I have seem them used to store simple settings before.

I need to pass several on/off options to a function, and I\'d li

3条回答
  •  生来不讨喜
    2020-12-14 10:04

    You sure can do it in PHP.

    Let's say you have four booleans you want to store in a single value. That means we need four bits of storage space

    0000
    

    Each bit, when set individually, has a unique representation in decimal

    0001 = 1 // or 2^0
    0010 = 2 // or 2^1
    0100 = 4 // or 2^2
    1000 = 8 // or 2^3
    

    A common way to implement this is with bit masks to represent each option. PHP's error levels are done this way, for example.

    define( 'OPT_1', 1 );
    define( 'OPT_2', 2 );
    define( 'OPT_3', 4 );
    define( 'OPT_4', 8 );
    

    Then when you have an integer that represents 0 or more of these flags, you check with with the bitwise and operator which is &

    $options = bindec( '0101' );
    // can also be set like this
    // $options = OPT_1 | OPT_3;
    
    if ( $options & OPT_3 )
    {
      // option 3 is enabled
    }
    

    This operator works as such: only bits that are set in both operands are set in the result

    0101 // our options
    0100 // the value of OPT_3
    ----
    0100 // The decimal integer 4 evaluates as "true" in an expression
    

    If we checked it against OPT_2, then the result would look like this

    0101 // our options
    0010 // the value of OPT_2
    ----
    0000 // The decimal integer 0 evaluates as "false" in an expression
    

提交回复
热议问题