Is there an objective-c specific way to count bits in an integer

随声附和 提交于 2020-01-24 15:12:08

问题


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 has Integer.bitCount()
  • C++ sometimes has __popcount()
  • SQL has BIT_COUNT()

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.


回答1:


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);
}

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



来源:https://stackoverflow.com/questions/25747885/is-there-an-objective-c-specific-way-to-count-bits-in-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!