-3

I want to test whether any single bit is set in a C int. I don't care which bit it is.

Equivalent to

if (1 == count_bits (n)) 

I'm curious if there is a non-looping algorithm for this which does not require special hardware support.

3
  • 9
    Check if n is non-zero? Commented Oct 29, 2018 at 10:19
  • 3
    Your text might indicate, that you are looking for a == 0, but your code snippet indicates, that you want to check if exactly one bit is set. Can you please specify it? Commented Oct 29, 2018 at 10:19
  • 2
    In an int? How do you want negative values handled? Commented Oct 29, 2018 at 10:31

2 Answers 2

5

If only one bit is set, then the number is a power of two.

unsigned int IsPowerOfTwoNoLoop(unsigned int input) { unsigned int temp = input; if(0 == input) { return 0; } temp -= 1; /*Example of the logic:*/ /* 0100 (4 DEC) - 1 = 0011 0011 & 0100 = 0000 */ if (temp & input) /* if not zero - not pow of two */ { printf("%u Is NOT the power of two !\n", input); return 0; } printf("%u Is the power of two !\n", input); return 1; } 
Sign up to request clarification or add additional context in comments.

3 Comments

I would suggest to use uint32_t instead of unsigned int. Why don't you accept any digit and reinterpret them as an unsigned value in your function?
Review: it would be much clearer (=better) to return bool from this function.
1

The simplest way is probably to convert to an unsigned type.

Then we are simply testing whether we have an exact power of two.

We can use a simple observation that these are the only non-zero numbers that have no bits in common with n-1:

bool is_power_of_two(unsigned int n) { return n && ! (n & (n-1)); } 

2 Comments

"This code falsely returns one when input is zero. – Eric Postpischil"
Oops - I mistakenly thought I'd taken that into account, and failed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.