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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 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, 2024 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, 2024 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, 2024 by avibootz
...