How to remove a bit from a number and shift all bits to the right to fill the gap in VB.NET

1 Answer

0 votes
Imports System

Module RemoveBitAndShiftProgram

    '---------------------------------------------------------------
    ' removeBitAndShift(number, position)
    '
    ' Removes the bit at the given position and shifts all higher bits right.
    '
    ' Example:
    '   number = 22 (10110)
    '   position = 2 (0 = LSB)
    '
    '   Bits: 1 0 1 1 0
    '             ^ remove this bit
    '
    '   left  = bits above removed bit
    '   right = bits below removed bit
    '
    '   result = (left << position) OR right
    '---------------------------------------------------------------
    Function removeBitAndShift(number As Integer, position As Integer) As Integer
        Dim leftPart As Integer = number >> (position + 1)          ' bits above removed bit
        Dim rightPart As Integer = number And ((1 << position) - 1) ' bits below removed bit

        Return (leftPart << position) Or rightPart                  ' merge shifted left + right
    End Function

    '---------------------------------------------------------------
    ' printBinary(value)
    '
    '  VB.NET binary printing:
    '   Convert.ToString(value, 2) → binary string
    '   PadLeft(32, "0"c) → pad to 32 bits
    '   Insert spaces every 4 bits for readability
    '---------------------------------------------------------------
    Sub printBinary(value As Integer)
        Dim binary As String = Convert.ToString(value, 2).PadLeft(32, "0"c)

        For i As Integer = 0 To binary.Length - 1
            Console.Write(binary(i))
            If (i + 1) Mod 4 = 0 Then Console.Write(" ")
        Next
    End Sub

    Sub Main()
        Dim number As Integer = 22
        Dim position As Integer = 2   ' remove bit 2 (0 = LSB)

        Console.WriteLine("Original number in binary:")
        printBinary(number)

        Dim result As Integer = removeBitAndShift(number, position)

        Console.WriteLine()
        Console.WriteLine()
        Console.WriteLine("Number after removing bit " & position &
                          " and shifting remaining bits:")
        printBinary(result)

        Console.WriteLine()
        Console.WriteLine()
        Console.WriteLine("Result as integer: " & result)
    End Sub

End Module



' run:
'
' Original number in binary:
' 0000 0000 0000 0000 0000 0000 0001 0110 
' 
' Number after removing bit 2 and shifting remaining bits:
' 0000 0000 0000 0000 0000 0000 0000 1010 
' 
' Result as integer: 10
'

 



answered Jun 23 by avibootz
edited Jun 24 by avibootz

Related questions

...