简体   繁体   中英

Excluding values that don't fit the mask - Bitwise operations in mySQL

I need help solving a problem. I have a User with a Bitmask-Value, let's say 10010001.
Column name is value_1. In this column I have this values to compare with:

|--|----------|  
|id|   value_1|
|--|----------|
| 1| 00000001 |
| 2| 10010001 | 
| 3| 00000010 | 
| 4| 10000001 |
| 5| 10011001 |
|--|----------|  

My query is this:

select value_1 from testdb
where b'10010001' & value_1;

My result is ID 1,2,4,5
This looks fine - but how can I exclude id 5 because the lowest 4th bit (counting from the right) is not in source?

Make sure that the combined bits of value_1's value and mask do not result in a number that exceeds the mask as a number.

where (b'10010001' & value_1) and (cast((b'10010001' | value_1) as unsigned) <= cast(b'10010001' as unsigned))

Exceeding means that at least one bit is present in value_1's value but not in the mask (source).

Test ithere

assuming your value_1 data type is string Try using a proper casting

    select value_1 from testdb
    where cast( '10010001' as unsigned )  & cast( value_1 as unsigned ) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM