有没有一种Objective-C特定的方式来对整数进行计数 [英] Is there an objective-c specific way to count bits in an integer

查看:91
本文介绍了有没有一种Objective-C特定的方式来对整数进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我在objective-c中的32位整数中设置为1的位进行计数.某些语言将其作为单个调用:

I'd like to count the bits set to 1 in my 32-bit integer in objective-c. Some languages have this as a single call:

  • Java具有Integer.bitCount()
  • C ++有时具有__popcount()
  • SQL具有BIT_COUNT()

Objective-C是否等效?否则,我将使用:

Is there an equivalent for Objective-C? Otherwise I'll use :

-(int32_t) BitCounter:(int32_t) v
{
    v = v - ((v >> 1) & 0x55555555);
    v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
    return (((v + (v >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}

...这很好,但是某些处理器将其作为内置在处理器中的单个命令使用,由于它处于时间紧迫的循环中,因此我自然希望利用它.

...which is fine, but some processors have it as a single command built in to the processor and naturally I'd like to take advantage of that since it's in a time critical loop.

推荐答案

gcc,叮当声具有

gcc, clang et al have __builtin_popcount, which is a C built-in which can be called from Objective-C:

-(int32_t) BitCounter:(int32_t) v
{
    return __builtin_popcount(v);
}

在具有SSE 4.2的现代x86平台上,应将其编译为一条指令(POPCNT).

On a modern x86 platform with SSE 4.2 this should compile to a single instruction (POPCNT).

这篇关于有没有一种Objective-C特定的方式来对整数进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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