iOS - SQLite - 是否有BIT_COUNT等价物

时间:2013-12-05 12:42:04

标签: iphone sql objective-c sqlite

我有一个场景,我需要计算1's数据库中0's的二进制表示的位(BIGINTSQLite)。这可以通过SQLBIT_COUNT轻松完成,但SQLite似乎不支持。

有人知道BIT_COUNT中的任何SQLite等效内容吗?我一直在谷歌上搜索,没有运气。

我在iOS上使用它,但我不认为这对这个问题非常重要;我也通过FMDB调用SQLite。

2 个答案:

答案 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 (
...
)

))))))