Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- MySQL can handle hexa digits well (0x0020 == 32 == b0100000)
- Hexa digits are easier to read and write, than binary numbers. Actually it processes the binary logical operations.
- flag_a = 0x0001
- flag_b = 0x0002
- flag_c = 0x0004
- flag_d = 0x0008
- flag_e = 0x0010
- flag_f = 0x0020
- ...
- Theorem:
- ^^^^^^^
- bit union: |
- 0100 (4)
- 0010 (2)
- -----------
- | 0110 (6)
- bit section: &
- 0110 (6)
- 0010 (2)
- -----------
- & 0010 (2)
- bit abstraction: & ~
- 0110 (6)
- 0010 (2)
- .........
- 0110 (6)
- 1101 (~2)
- -----------
- &~0100 (4)
- Examples with numbers:
- ^^^^^^^^^^^^^^^^^^^^^
- CHECK:
- SELECT 33 & 0x0020; # is flag set? -> yes 32
- SELECT 12 & 0x0020; # is flag set? -> no 0
- SET:
- SELECT (33 | 0x0020); # -> 33
- SELECT (10 | 0x0020); # -> 42
- DELETE:
- SELECT (33 & ~ 0x0020); # -> 1
- TOGGLE:
- SELECT (33 ^ 0x0020); # -> 1
- SELECT ((33 ^ 0x0020) ^ 0x0020); # -> 33
- Database examples:
- ^^^^^^^^^^^^^^^^^
- [ CHECK ]
- Is flag set?
- SELECT * FROM table WHERE flags & 0x0020 = 0x0020 ; # this is nice and readable
- SELECT * FROM table WHERE (flags & 0x0020); # this is easy
- Is flag unset?
- SELECT * FROM table WHERE flags & 0x0020 = 0; # this is nice and readable
- SELECT * FROM table WHERE !(flags & 0x0020); # this is easy
- [ SET ]
- UPDATE table SET flags = flags | 0x0020;
- [ DELETE ]
- UPDATE table SET flags = flags & ~0x0020;
- [ TOGGLE ]
- UPDATE table SET flags = flags ^ 0x0020;
- [ Multiple flag CHECKing ]
- Let user privileges
- PRIV_ADMIN = 0x0001;
- PRIV_LEARNER = 0x0008;
- Get users which have ADMIN or LEARNER privileges!
- SELECT * FROM users WHERE priv & (0x0008 | 0x0001) = (0x0008 | 0x0001);
- Get users which have both ADMIN and LEARNER privileges!
- SELECT * FROM users WHERE priv & (0x0008 | 0x0001) > 0; # this is nice and readable
- SELECT * FROM users WHERE (priv & (0x0008 | 0x0001)); # this is easy
- Get users which have nor ADMIN, nor LEARNER privileges!
- SELECT * FROM users WHERE priv & (0x0008 | 0x0001) = 0; # this is nice and readable
- SELECT * FROM users WHERE !(priv & (0x0008 | 0x0001)); # this is easy
- [ Multiple flag SETting ]
- Let user be an ADMIN and a LEARNER too!
- UPDATE users SET priv = priv | (0x0008 | 0x0001);
- [ Multiple flag DELETEing ]
- Delete ADMIN and LEARNER privilege of the user!
- UPDATE users SET priv = priv & ~(0x0008 | 0x0001);
- [ SET and DELETE flags at the same time ]
- Give the user ADMIN privilege but take LEARNER privilege away!
- UPDATE users SET priv = priv | (0x0001) & ~ (0x0008);
- In this case we can use multiple flags to SET and UNSET using the | operation.
- UPDATE users SET priv = priv | (0x0001 | 0x0020) & ~ (0x0008 | 0x0040);
Advertisement
Add Comment
Please, Sign In to add comment