Matt Parkins
Matt Parkins

Reputation: 24688

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

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:

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.

Upvotes: 4

Views: 834

Answers (1)

Paul R
Paul R

Reputation: 212959

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).

Upvotes: 5

Related Questions