Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,037 questions

40,797 answers

573 users

How to count the trailing zeros in a binary number in C#

3 Answers

0 votes
using System;

class Program {
    static int CountTrailingZeros(int number) {
        int zeros = 0;
       
        int INT_SIZE = sizeof(int) * 8;
        
        for (int i = 0; i < INT_SIZE; i++) {
            if (((number >> i) & 1) != 0) {
                break;
            }
            zeros++;
        } 
         
        return zeros;
    }
    
    static void Main(string[] args) {
        int number = 80; // 1010000
 
        Console.WriteLine("Number of Trailing Zeros: " + CountTrailingZeros(number));
   }
}




/*
run:
   
Number of Trailing Zeros: 4
   
*/

 





answered Apr 7 by avibootz
0 votes
using System;

class Program {
    static int CountTrailingZeros(int number) {
        int INT_SIZE = sizeof(int) * 8;
        
        int mask = 1;
        
        for (int i = 0; i < INT_SIZE; i++, mask <<= 1) {
            if ((number & mask) != 0) {
                return i;
            }
        }

        return -1;
    }
    
    static void Main(string[] args) {
        int number = 80; // 1010000
 
        Console.WriteLine("Number of Trailing Zeros: " + CountTrailingZeros(number));
   }
}




/*
run:
   
Number of Trailing Zeros: 4
   
*/

 





answered Apr 7 by avibootz
0 votes
using System;

class Program {
    static int CountTrailingZeros(int number) {
        int[] BitPosition = {
            32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17,
            0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18
        };
        
        return BitPosition[(number & -number) % 37];
    }

    static void Main(string[] args) {
        int number = 80; // 1010000
 
        Console.WriteLine("Number of Trailing Zeros: " + CountTrailingZeros(number));
   }
}




/*
run:
   
Number of Trailing Zeros: 4
   
*/

 





answered Apr 7 by avibootz

Related questions

...