【问题标题】:__builtin_popcount - is this equivalent in C#?__builtin_popcount - 这在 C# 中是等价的吗?
【发布时间】:2014-11-19 05:24:20
【问题描述】:

https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

——内置函数:int __builtin_popcount (unsigned int x) 返回 x 中 1 的位数。

所以也一样,我在c#中尝试了以下代码

        long l8 = 9;
        int iCont = Convert.ToString(l8, 2).Split('0').ToList().FindAll(x=>x=="1").Count;

我想在堆栈溢出中仔细检查这个问题,如果这是我所做的错误,或者是否有任何内置函数做同样的事情。

【问题讨论】:

    标签: c# gcc


    【解决方案1】:

    不,不是。它会在二进制表示中具有相邻 1 的任何数字上失败,因为它们将在 Split('0') 之后的一个字符串中一起出现,因此与 (x => x == "1") 不匹配。例如,尝试 3。

    因为string实现了IEnumerable<char>,所以你可以在直接看字符的同时使用和你类似的思路:

    Convert.ToString(l8, 2).Count(c => c == '1')

    当然还有其他cleverer solutions

    【讨论】:

    • 谢谢你,我用那个聪明的解决方案做了这个。不过完全测试它
    • static int __builtin_popcount(long i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333);返回 (int)(((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多