我有一个场景,我需要计算1's
数据库中0's
的二进制表示的位(BIGINT
和SQLite
)。这可以通过SQL
在BIT_COUNT
轻松完成,但SQLite
似乎不支持。
有人知道BIT_COUNT
中的任何SQLite
等效内容吗?我一直在谷歌上搜索,没有运气。
我在iOS上使用它,但我不认为这对这个问题非常重要;我也通过FMDB调用SQLite。
答案 0 :(得分:1)
不幸的是没有。 我认为唯一可行的解决方案是添加一个新列,其中包含在保存期间设置的1的数量,以及计算1的数量的应用程序级别函数。
答案 1 :(得分:0)
可以使用following nugget中描述的方法。
由于sqlite在最有效的实现中会将乘数值上转换为REAL,因此我们必须使用“仅加法和移位”实现。
//types and constants used in the functions below
//uint64_t is an unsigned 64-bit integer variable type (defined in C99 version of C language)
const uint64_t m1 = 0x5555555555555555; //binary: 0101...
const uint64_t m2 = 0x3333333333333333; //binary: 00110011..
const uint64_t m4 = 0x0f0f0f0f0f0f0f0f; //binary: 4 zeros, 4 ones ...
...
//This uses fewer arithmetic operations than any other known
//implementation on machines with slow multiplication.
//This algorithm uses 17 arithmetic operations.
int popcount64b(uint64_t x)
{
x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits
x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits
x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits
x += x >> 8; //put count of each 16 bits into their lowest 8 bits
x += x >> 16; //put count of each 32 bits into their lowest 8 bits
x += x >> 32; //put count of each 64 bits into their lowest 8 bits
return x & 0x7f;
}
在SQLlite中实现,如下所示:
SELECT a, b, (x + (x >> 32)) & 0x7f AS Distance FROM (
SELECT a, b, x + (x >> 16) AS x FROM (
SELECT a, b, x + (x >> 8) AS x FROM (
SELECT a, b, (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f AS x FROM (
SELECT a, b, (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333) AS x FROM (
SELECT a, b, x - ((x >> 1) & 0x5555555555555555) AS x FROM (
-- In my case, I'm counting the bits from an x-or.
SELECT a, b, (~(a&b))&(a|b) AS x FROM (
...
)
))))))