### hiroshima_boy's blog

By hiroshima_boy, history, 3 years ago,

1.) __builtin_popcount(x): Counts the number of one’s(set bits) in an integer(long/long long).

Ex- int x=5;
cout<<__builtin_popcount(x)<<endl;   //returns 2.

If x is of long type,we can use __builtin_popcountl(x) If x is of long long type,we can use __builtin_popcountll(x)

2.) __builtin_parity(x): Checks the Parity of a number.Returns true(1) if the number has odd parity(odd number of set bits) else it returns false(0) for even parity(even number of set bits).

Ex- int x=5;
cout<<__builtin_parity(x)<<endl;   //returns 0.

If x is of long type,we can use __builtin_parityl(x) If x is of long long type,we can use __builtin_parityll(x)

3.) __builtin_clz(x): Counts the leading number of zeros of the integer(long/long long).

If x is of long type,we can use __builtin_clzl(x) If x is of long long type,we can use __builtin_clzll(x)

Ex- int x=16;       // 00000000 00000000 00000000 00010000 (32 bits)
cout<<__builtin_clz(x)<<endl;   //returns 27.

Ex- long x=16;       // 00000000 00000000 00000000 00010000 (32 bits)
cout<<__builtin_clzl(x)<<endl;   //returns 27.

Ex- long long x=16;       // 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00010000 (64 bits)
cout<<__builtin_clzll(x)<<endl;   //returns 59.

4.) __builtin_ctz(x): Counts the trailing number of zeros of the integer(long/long long).

If x is of long type,we can use __builtin_ctzl(x) If x is of long long type,we can use __builtin_ctzll(x)

Ex- int x=16;       // 00000000 00000000 00000000 00010000 (32 bits)
cout<<__builtin_ctz(x)<<endl;   //returns 4.

In case of both __builtin_ctzl(x) and __builtin_ctzll(x),the answer is same.

• +7

 » 3 years ago, # |   +1 There's also __builtin_ffs(x) (Find First Set) which returns (the index of the least significant bits of x) + 1.
•  » » 3 years ago, # ^ |   0 There's also __lg(x) which returns the index of the highest set bit. More about it.
 » 18 months ago, # |   0 So I need to find the leading zeroes of say 1e15 , and I used builtinclzll(x) , where x is initialized as long long data type , but at the end , the function returns the leading zeroes from the 32 bit representation. I also cross-verified it using builtinclzll(1e15) , but the result is still the same. help pls
•  » » 18 months ago, # ^ |   0 the underscores were ignored , don't know why , but I used the correct function
•  » » 18 months ago, # ^ |   +3 got the mistake , really sorry to disturb you
 » 2 months ago, # | ← Rev. 2 →   0 I have faced the word 'parity' many times when I have worked with bits. Can anyone explain what parity really is?
•  » » 2 months ago, # ^ |   -8 If a number is odd, its bit representation will always contain a set bit(1) at the last position, we say it has odd parity. Similarly, if it is even, its bit representation will always contain the reset bit(0) at the last position, we say it has even parity.