How to check if exactly one bit is set in an int?

Fabian

I have an std::uint32_t and want to check if exactly one bit is set. How can I do this without iterating over all bits like this? In other words, can the following function be simplified?

static inline bool isExactlyOneBitSet(std::uint32_t bits)
{
    return ((bits & 1) == bits
        || (bits & 1 << 1) == bits
        || (bits & 1 << 2) == bits
        // ...
        || (bits & 1 << 31) == bits
        );
}

Bonus: It would be nice if the return value was the one found bit or else 0.

static inline bool isExactlyOneBitSet(std::uint32_t bits)
{
if (bits & 1) {return 1;}
else if  (bits & 1 << 1) {return 1 << 1;};
//...
else if  (bits & 1 << 31) {return 1 << 31;};

return 0;
}
Abhishek Keshri

So you want to know if a number is power of 2 or not? Well there is a famous algorithm for that, you can simply do,

check_bit(std::uint32_t bits)
{
    return bits && !(bits & (bits-1));
}

Any power of 2 when subtracted by 1 is all 1s. e.g,

4 - 1 = 3 (011)
8 - 1 = 7 (0111)

The bitwise and of any power of 2 and any number 1 less than it will give 0. So we can verify if a number is power of 2 or not by using the expression, n&(n-1).

It will fail when n=0, so we have to add an extra and condition.

For finding the position of bit, you can do:

int findSetBit(std::uint32_t bits)
{
    if (!(bits && !(bits & (bits-1))))
        return 0;
    return log2(bits) + 1;
}

Extra Stuffs

In gcc, you can use __builtin_popcount(), to find the count of set bits in any number.

#include <iostream>

int main()
{
   std::cout << __builtin_popcount (4) << "\n";
   std::cout << __builtin_popcount (3) << "\n";

   return 0;
}

Then check if count is equal to 1 or not.

Regarding count, there is another famous algorithm, Brian Kernighan’s Algorithm. Google it up, it finds count in log(n) time.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How exactly does Python check through a list?

分類Dev

Check if exists exactly one attribute of the node and return value of this attribute in XPAth

分類Dev

How to change the background color for exactly one line?

分類Dev

How to check if my software is 32-bit or 64-bit

分類Dev

How to check if isset is not set?

分類Dev

How to cast signed int to 15 bit bit-field?

分類Dev

how to match exactly one word among the others in REGEX 'or'(|) condition

分類Dev

how to set the eighth bit to zero (reading data from smarcard)

分類Dev

How do I reduce the cost of set_bit in Postgres?

分類Dev

How can I switch a 32-bit installation to a 64-bit one?

分類Dev

How to check if one is using a raspberry pi?

分類Dev

How to check one type conforms to another/typehint

分類Dev

how to check hover mouse in one element

分類Dev

Set bit counting

分類Dev

Any one know how exactly IL/CLR generates Local Functions C#7

分類Dev

How can I set mouse sensitivity exactly the same in Windows 7 and Mac OS X Lion?

分類Dev

How to set a variable in one class and get it in another

分類Dev

How to set Spinner in one line with EditText

分類Dev

How to set that one variable is greater then the other in Python?

分類Dev

How to set one TableColumn to grow with TableView?

分類Dev

Regex: How to capture one set of parenthesis, but not the next

分類Dev

How to set setAlpha() on one item in a GridView?

分類Dev

How does one set boot priority to cd?

分類Dev

Check if bit has toggled in C

分類Dev

How do I check for all entries that has a certain bit/flag/mask in them

分類Dev

Check how many clicks have occurred on a bit.ly link present in a particular tweet

分類Dev

How can I create a typesafe handle that behaves almost exactly like int64_t, but disallow implicit conversions between handle types?

分類Dev

Regex match URL with exactly one folder deep

分類Dev

JSON Schema: Validate that exactly one property is present

Related 関連記事

  1. 1

    How exactly does Python check through a list?

  2. 2

    Check if exists exactly one attribute of the node and return value of this attribute in XPAth

  3. 3

    How to change the background color for exactly one line?

  4. 4

    How to check if my software is 32-bit or 64-bit

  5. 5

    How to check if isset is not set?

  6. 6

    How to cast signed int to 15 bit bit-field?

  7. 7

    how to match exactly one word among the others in REGEX 'or'(|) condition

  8. 8

    how to set the eighth bit to zero (reading data from smarcard)

  9. 9

    How do I reduce the cost of set_bit in Postgres?

  10. 10

    How can I switch a 32-bit installation to a 64-bit one?

  11. 11

    How to check if one is using a raspberry pi?

  12. 12

    How to check one type conforms to another/typehint

  13. 13

    how to check hover mouse in one element

  14. 14

    Set bit counting

  15. 15

    Any one know how exactly IL/CLR generates Local Functions C#7

  16. 16

    How can I set mouse sensitivity exactly the same in Windows 7 and Mac OS X Lion?

  17. 17

    How to set a variable in one class and get it in another

  18. 18

    How to set Spinner in one line with EditText

  19. 19

    How to set that one variable is greater then the other in Python?

  20. 20

    How to set one TableColumn to grow with TableView?

  21. 21

    Regex: How to capture one set of parenthesis, but not the next

  22. 22

    How to set setAlpha() on one item in a GridView?

  23. 23

    How does one set boot priority to cd?

  24. 24

    Check if bit has toggled in C

  25. 25

    How do I check for all entries that has a certain bit/flag/mask in them

  26. 26

    Check how many clicks have occurred on a bit.ly link present in a particular tweet

  27. 27

    How can I create a typesafe handle that behaves almost exactly like int64_t, but disallow implicit conversions between handle types?

  28. 28

    Regex match URL with exactly one folder deep

  29. 29

    JSON Schema: Validate that exactly one property is present

ホットタグ

アーカイブ