Set permissions in binary

前端 未结 5 2005
说谎
说谎 2020-12-29 16:06

I saw in school a system that set permissions using binary string.

Let\'s say 101001 = 41

So :

  • 1 can be permission to page 1
  • 2 can b
5条回答
  •  猫巷女王i
    2020-12-29 16:47

    You can use & operator and check against those flags.

    $READ = 8;
    $WRITE = 1;
    $EXECUTE = 32;
    $permissions = 41;
    if ($permissions & $READ) {
       // do smth
    }
    if ($permissions & $WRITE ) {
       // do smth
    }
    if ($permissions & $EXECUTE ) {
       // do smth
    }
    

    Let me explain it. If you have bits 1001 (9). You just check forth bit (1000) with 1001. You just multiply EVERY bit of $permissions variable and bit number. Result will be 1000. It's convertible to true value. So you have flag here. If check third bit (0100) it will result in 0000 and it's false value. So you haven't got permissions here.

提交回复
热议问题