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.

39,971 questions

51,913 answers

573 users

How to count set bits of an integer in VB.NET

2 Answers

0 votes
Imports System 

Public Class Program
	Public Shared Function count_set_bits(ByVal num As Integer) As Integer
        Dim count as Integer = 0
           
        Do While num > 0
            count += num And 1
            num >>= 1
        Loop
           
        return count 
    End Function
    
    Public Shared Sub Main(ByVal args As String())
		Console.WriteLine("Total Set Bits : {0}", count_set_bits(10)) ' 1010
		
		Console.WriteLine("Total Set Bits : {0}", count_set_bits(45)) ' 00101101
    End Sub
End Class
 
 
 
' run:
'
' Total Set Bits : 2
' Total Set Bits : 4
'

 



answered May 9, 2019 by avibootz
edited Dec 14, 2023 by avibootz
0 votes
Imports System 

Public Class Program
	Public Shared Function count_set_bits(ByVal num As Integer) As Integer
        Dim count As Integer = 0
        
		while (num > 0)
            count += 1
            num = num And (num - 1)
        End While
        
		Return count
    End Function
    
    Public Shared Sub Main(ByVal args As String())
		Console.WriteLine("Total Set Bits : {0}", count_set_bits(10)) ' 1010
		
		Console.WriteLine("Total Set Bits : {0}", count_set_bits(45)) ' 00101101
    End Sub
End Class
 
 
 
' run:
'
' Total Set Bits : 2
' Total Set Bits : 4
'

 



answered Dec 14, 2023 by avibootz

Related questions

1 answer 136 views
1 answer 186 views
1 answer 99 views
1 answer 91 views
1 answer 97 views
...