更新整数列中的特定位 [英] update specific bit in integer column
本文介绍了更新整数列中的特定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个mysql表,其中用户权限存储为位掩码:
I have a mysql table where user permissions are stored as a bitmask:
|user | permissions |
| Admin | 31 |
| User | 13 |
16 8 4 2 1
Admin -> 1 1 1 1 1 -> 16 + 8 + 4 + 2 + 1 -> 31
User -> 0 1 1 0 1 -> 8 + 4 + 1 -> 13
现在,我想使用SQL查询为每个用户添加权限. 假设我想为所有人添加权限16,而无需另外修改.
Now I want to add a permission for every user with an sql query. Let's say I want to add the permission 16 for everyone without modifying another bit.
UPDATE users SET permission = ????
我该怎么做?
推荐答案
要添加权限16,您只需说
To add permission 16, you just say
UPDATE users SET permission = permission | 16;
按位或运算符将打开位.要关闭它们,请使用AND操作加上您要关闭的位的补码:
The bitwise OR operator will turn bits on. To turn them off, use a AND operation with the complement of the bit you want off:
UPDATE users SET permission = permission & ~16
这篇关于更新整数列中的特定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文