Find the position of rightmost set bit of integer in vb.net

Vb program for Find the position of rightmost set bit of integer. Here problem description and explanation.

' Include namespace system
Imports System 
'  Vb.net Program for
'  Find position of rightmost set bit

Public Class BitPosition
    '  Finding the right most active bit position
    Public Sub rightmostActiveBit(ByVal n As Integer)
        if (n <= 0) Then
            Return
        End If
        '    Example 
        '    ———————
        '    n    = 320
        '    n    = (00101000000)   Binary
        '    -n   = (11011000000)   (2s)
        '    Calculate log2 
        '    ——————————————
        '    Formula : log(n & -n) / log(2) + 1
        '    -----------------------------------
        '    log(320 & -320) / log(2) + 1)
        '    Here : log(320 & -320) = log(64) = 4.158883
        '           log(2)  = 0.693147    
        '    (4.158883 / 0.693147) + 1 = (7) position
        '    ————————————————————————————————————————
        '  Calculate rightmost active bits
        Dim result As Integer = CInt((Math.Log(n And -n) / Math.Log(2) + 1))
        Console.WriteLine(" Number : " + 
                          n.ToString() + " Result : " + 
                          result.ToString())
    End Sub
    Public Shared Sub Main(ByVal args As String())
        Dim task As BitPosition = New BitPosition()
        '  Test Cases
        '  320 = Binary(101000000)
        task.rightmostActiveBit(320)
        '  (1000) = Binary(1111101000)
        task.rightmostActiveBit(1000)
        '  (153) = Binary(10011001)
        task.rightmostActiveBit(153)
        '  (354) = Binary(101100010)
        task.rightmostActiveBit(354)
        '  160 = Binary(10100000)
        task.rightmostActiveBit(160)
    End Sub
End Class

Output

 Number : 320 Result : 7
 Number : 1000 Result : 4
 Number : 153 Result : 1
 Number : 354 Result : 2
 Number : 160 Result : 6


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved