替代按位运算 [英] Alternative to bitwise operation

查看:60
本文介绍了替代按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景: 我说有4个复选框,用户可以任意组合选择这些复选框(它们也具有不选择单个复选框的功能).我必须将这4个选项存储到单个列中.我认为最好的选择是使用二进制表示形式进行存储

Scenario : I have say 4 check boxes and users can select those checkboxes in any combination(they also have the power to not select even a single check box). I have to store these 4 options to a single column. I think the best option is to store using binary representation

option1 has the constant value 1 
option2 has the constant value 2
option3 has the constant value 4
option4 has the constant value 8

因此,如果客户选择option2和option4,则存储在数据库中的值将为2 + 8,即:10,如果客户选择option1,option4和option8,则值将为1 + 4 + 8,即13

So if the customer selects option2 and option4, then the value that is stored in the DB will be 2 + 8 ie: 10, if customer selects option1, option4 and option8 the value will be 1 + 4 + 8 which is 13.

当我从mysql查询时,我也可以使用

Also when I query from mysql I can use

Select * from option_table where (option & 4)=4;

如果我要检索选择了option3的行.

if I want to retrieve rows where option3 is selected.

但是由于某种原因,我不能使用这种方法,或者只是说我需要知道将这些多个值存储在单个列中的下一个最佳选择是什么?

But for some reason I cannot use this approach, or just say I need to know what's the next best option to store these multiple values in a single column ?

推荐答案

一种替代方法是将质数相乘.要选择,请选择素数在该列值中的模数为0的列.

An alternative could be to multiply prime numbers. To select, you would select columns where the modulus of the prime number into the value of the column is 0.

示例:

值1:2
值2:3
值3:5
值4:7

Value 1: 2
Value 2: 3
Value 3: 5
Value 4: 7

值2& 3将是3 * 5 = 15
值1、2、3、4将是2 * 3 * 5 * 7 = 210

Value 2 & 3 would be 3*5 = 15
Values 1, 2, 3, 4 would be 2*3*5*7 = 210

要获取值为1的行,请选择value % 2 == 0

To get the rows where value 1 is on, select where value % 2 == 0

这篇关于替代按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆