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

后端 未结 3 862
醉梦人生
醉梦人生 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:26

    It works pretty much the same way in both languages, a side by side comparison:

    C:

    #include 
    #include 
    
    #define FLAG_ONE 0x0001
    #define FLAG_TWO 0x0002
    #define FLAG_THREE 0x0004
    #define FLAG_FOUR 0x0008
    #define FLAG_ALL (FLAG_ONE|FLAG_TWO|FLAG_THREE|FLAG_FOUR)
    
    void make_waffles(void)
    {
       printf("Yummy! We Love Waffles!!!\n");
    }
    
    void do_something(uint32_t flags)
    {
        if (flags & FLAG_TWO)
             make_waffles();
    }
    
    int main(void)
    {
        uint32_t flags;
    
        flags |= FLAG_ALL;
    
        /* Lets make some waffles! */
        do_something(flags);
    
        return 0;
    }
    

    PHP:

    
    

    Note, you don't absolutely need to use constants, I just use them out of habit. Both examples will run, I compiled the C version via gcc -Wall flags.c -o flags. Change flags in either example to anything but FLAG_TWO or FLAG_ALL and (sadly) no waffles will be made.

    In the C version, you don't have to tickle the preprocessor, it could quite easily be an enum, etc - that's an exercise for the reader.

提交回复
热议问题