Mysql Bitwise operations and filter

二次信任 提交于 2019-12-04 03:07:51

You can use bitwise operators in MySQL:

http://dev.mysql.com/doc/refman/5.0/en/bit-functions.html

Example:

SELECT (data1 & b'00101011') as output1 FROM ......

Quick test:

SELECT (b'10110110' & b'00101011') as output1

This does a bitwise AND with the binary pattern of the mask you specified.
See the above link for more toys.

The only way I know of doing what you want is something like

SELECT ((data >> 2) & 8) | ((data >> 1) & 4) | (data & 3) FROM ...

Obviously, you'll have to construct the expression based on your mask; it's not very difficult to do, just a bit tedious — you basically need to loop over the bits in the mask, something like this:

var mask = 0b00101011;
var parts = new Array();
var shift = 0;
var unshift = 0;
while (mask > 0) {
    while ((mask & 1) == 0) {
        shift = shift + 1;
        mask = mask >> 1;
    }
    submask = 0;
    while ((mask & 1) == 1) {
        submask = submask + (1 << unshift);
        unshift = unshift + 1;
        mask = mask >> 1;
    }
    parts.push( "((data >> " + shift + ") & " + submask + ")" );
}
var expr = parts.join( " | " );
console.log(expr);

The example code above is in JavaScript, so you can run it as a snippet here and get:

((data >> 0) & 3) | ((data >> 1) & 4) | ((data >> 2) & 8)

logged to the console, but it should be pretty easy to port to other languages.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!