Hamming Weight in Swift

Is the hamming weight (number of bits set) available somehow in swift? I have seen the __builtin_popcount function mentioned in reference to LLVM/Clang, but can't get swift to recognize it...


I have the following function which works, but I would like to take advantage of the hardware instruction on chips that have it...

func numOfSetBits (num:UInt64) -> UInt64 {
    var i:UInt64 = num
  
    i = (((i >> 1)  & 0b0101010101010101010101010101010101010101010101010101010101010101)
        + i         & 0b0101010101010101010101010101010101010101010101010101010101010101);
    i = (((i >> 2)  & 0b0011001100110011001100110011001100110011001100110011001100110011)
        + i         & 0b0011001100110011001100110011001100110011001100110011001100110011);
    i = (((i >> 4)  & 0b0000111100001111000011110000111100001111000011110000111100001111)
        + i         & 0b0000111100001111000011110000111100001111000011110000111100001111);
    i = (((i >> 8)  & 0b0000000011111111000000001111111100000000111111110000000011111111)
        + i         & 0b0000000011111111000000001111111100000000111111110000000011111111);
    i = (((i >> 16) & 0b0000000000000000111111111111111100000000000000001111111111111111)
        + i         & 0b0000000000000000111111111111111100000000000000001111111111111111);
    i = (((i >> 32) & 0b0000000000000000000000000000000011111111111111111111111111111111)
        + i         & 0b0000000000000000000000000000000011111111111111111111111111111111);
    return i;
}

Also, this only works for UInt64, and it would be nice to have a single efficient opperation for all integer types...

Post not yet marked as solved Up vote post of jonhull Down vote post of jonhull
603 views

Replies

I was just wondering about a related question around the count leading / trailing zeros instructions.