Imports System
Module ClearBitsRange
' Print bits of a 32-bit unsigned integer
Sub PrintBits(x As UInteger, labelStr As String)
Dim bits As String = Convert.ToString(x, 2).PadLeft(32, "0"c)
Console.WriteLine(labelStr & ": " & bits)
End Sub
' Clear bits in range [l, r] inclusive (0 = least significant bit)
Function ClearBits(x As UInteger, l As Integer, r As Integer) As UInteger
If l < 0 OrElse r > 31 OrElse l > r Then
Throw New ArgumentException("Invalid bit range")
End If
' maskLeft:
' Create a mask with 1s above bit r and 0s from bit r down to 0.
' Example: r = 5 → maskLeft = 11111111 11111111 11111111 11000000
Dim maskLeft As UInteger = (Not 0UI) << (r + 1)
PrintBits(maskLeft, "maskLeft ")
' maskRight:
' Create a mask with 1s below bit l and 0s from bit l upward.
' Example: l = 3 → maskRight = 00000000 00000000 00000000 00000111
Dim maskRight As UInteger = (1UI << l) - 1UI
PrintBits(maskRight, "maskRight")
' Combine both masks:
' maskLeft keeps bits above r.
' maskRight keeps bits below l.
' The range [l, r] becomes 0s.
Dim mask As UInteger = maskLeft Or maskRight
PrintBits(mask, "mask ")
Return x And mask
End Function
Sub Main()
Dim value As UInteger = &HFCF3F3FCUI ' &B11111100111111001111110011111100
Dim l As Integer = 3 ' start bit
Dim r As Integer = 10 ' end bit
Dim result As UInteger = ClearBits(value, l, r)
PrintBits(value, "Before ")
PrintBits(result, "After ")
End Sub
End Module
' run:
'
' maskLeft : 11111111111111111111100000000000
' maskRight: 00000000000000000000000000000111
' mask : 11111111111111111111100000000111
' Before : 11111100111100111111001111111100
' After : 11111100111100111111000000000100
'