如何在Sybase SQL Anywhere中模拟MySQL bit_count函数? [英] How to simulate the MySQL bit_count function in Sybase SQL Anywhere?

查看:130
本文介绍了如何在Sybase SQL Anywhere中模拟MySQL bit_count函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MySQL的bit_count函数在某些情况下非常有用:

MySQL's bit_count function is quite useful for some cases:

http://dev.mysql. com/doc/refman/5.5/en/bit-functions.html#function_bit-count

现在,我想在不支持该功能的其他数据库中使用该功能.最简单的方法是什么(无需创建存储函数,因为我无法在DDL级别上访问客户端数据库).

Now I would like to use that function in other databases, that do not support it. What's the simplest way to do it (without creating a stored function, as I do not have access to the client database on a DDL level).

这是一个非常详细的选项(对于TINYINT数据类型):

One pretty verbose option is this (for TINYINT data types):

SELECT (my_field &   1)      +
       (my_field &   2) >> 1 +
       (my_field &   4) >> 2 +
       (my_field &   8) >> 3 +
       (my_field &  16) >> 4 + 
        ...
       (my_field & 128) >> 7 
FROM my_table

对于Sybase SQL Anywhere,>>运算符似乎不可用,因此按2, 4, 8, 16进行除法也可以.

In the case of Sybase SQL Anywhere, the >> operator doesn't seem to be available, so a division by 2, 4, 8, 16 works as well.

还有其他更简单的选择吗?

Any other, less verbose options?

推荐答案

我发现这种算法在Java的IntegerLong类中略为冗长.不过,我完全不知道为什么它应该以这种方式工作:

I've found this algorithm that's a little less verbose in Java's Integer and Long classes. I'm completely oblivious to why it's supposed to work this way, though:

public static int bitCount(int i) {
    // HD, Figure 5-2
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    i = i + (i >>> 8);
    i = i + (i >>> 16);
    return i & 0x3f;
}

这篇关于如何在Sybase SQL Anywhere中模拟MySQL bit_count函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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