Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding trailing 0s in a binary number

Tags:

c

binary

How to find number of trailing 0s in a binary number?Based on K&R bitcount example of finding 1s in a binary number i modified it a bit to find the trailing 0s.

int bitcount(unsigned x)
{
  int b;
  for(b=0;x!=0;x>>=1)
      {
        if(x&01)
          break;
        else
          b++;
      }

I would like to review this method.

like image 233
Abhishek kumar Avatar asked Oct 18 '11 18:10

Abhishek kumar


People also ask

How do you find the binary trailing zeros?

Given an integer, count the number of trailing zeroes. For example, for n = 12, its binary representation is 1100 and number of trailing zero bits is 2. Examples : Input : 8 Output : 3 Binary of 8 is 1000, so there are three trailing zero bits.

What is the rule for trailing zeros?

To determine the number of significant figures in a number use the following 3 rules: Non-zero digits are always significant. Any zeros between two significant digits are significant. A final zero or trailing zeros in the decimal portion ONLY are significant.

How do you count the number of zeros in a binary number in Python?

You can get the number of zeros by subtracting ones(num) from the total number of digits.


1 Answers

Here's a way to compute the count in parallel for better efficiency:

unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
like image 115
sizzzzlerz Avatar answered Nov 17 '22 01:11

sizzzzlerz