How to use bitmask?

后端 未结 4 1002
無奈伤痛
無奈伤痛 2020-12-04 06:35

How do i use it in C++ ? when is it useful to use ?
Please give me an example of a problem where bitmask is used , how it actually works . Thanks!

4条回答
  •  庸人自扰
    2020-12-04 07:06

    Bitmasks are used when you want to encode multiple layers of information in a single number.

    So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit.

    rwx
    ---
    110
    

    110 in base 2 translates to 6 in base 10.

    So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission.

    Pseudocode:

    PERM_READ = 4
    PERM_WRITE = 2
    PERM_EXEC = 1
    
    user_permissions = 6
    
    if (user_permissions & PERM_READ == TRUE) then
      // this will be reached, as 6 & 4 is true
    fi
    

    You need a working understanding of binary representation of numbers and logical operators to understand bit fields.

提交回复
热议问题