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,890 questions

51,819 answers

573 users

How to round a number to the nearest power of 2 in VB.NET

1 Answer

0 votes
Module NearestPowerOfTwo

    ''' Rounds an unsigned integer to the nearest power of 2.
    ''' <returns>The nearest power of 2</returns>
    Function RoundToNearestPowerOf2(n As UInteger) As UInteger
        If n = 0 Then Return 0

        Dim prevPower As UInteger = 1UI << (31 - LeadingZeroCount(n))
        Dim nextPower As UInteger = prevPower << 1

        If n - prevPower < nextPower - n Then
            Return prevPower
        Else
            Return nextPower
        End If
    End Function

    ''' Counts leading zeros in a 32-bit unsigned integer.
    Function LeadingZeroCount(value As UInteger) As Integer
        Dim count As Integer = 0
        Dim mask As UInteger = &H80000000UI

        While (mask > 0 AndAlso (value And mask) = 0)
            count += 1
            mask >>= 1
        End While

        Return count
    End Function

    Sub Main()
        Dim num As UInteger = 37

        Console.WriteLine($"Nearest power of 2: {RoundToNearestPowerOf2(num)}")
    End Sub

End Module



' run:
'
' Nearest power of 2: 32
'

 



answered Oct 31, 2025 by avibootz

Related questions

1 answer 41 views
1 answer 33 views
4 answers 142 views
3 answers 153 views
2 answers 93 views
1 answer 109 views
1 answer 58 views
...