gpt4 book ai didi

c# - __builtin_popcount - 这在 C# 中是否等效?

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:54 24 4
gpt4 key购买 nike

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;

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

最佳答案

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

因为 string工具 IEnumerable<char> ,您可以在直接查看字符时使用与您类似的想法:

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

还有其他cleverer solutions ,当然。

关于c# - __builtin_popcount - 这在 C# 中是否等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27009570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com