How to copy bits from M into N (numbers) between bit positions i and j (edge‑case‑safe) in VB.NET

1 Answer

0 votes
Imports System

Module CopyBitsModule

    '
    '   Handles edge cases:
    '   - Validates i and j
    '   - Prevents undefined behavior from shifting by ≥ 64 bits
    '   - Masks M so only the required bits are copied
    '

    ' Convert unsigned 64‑bit integer to binary string without leading zeros
    Function ToBinary(x As ULong) As String
        If x = 0UL Then
            Return "0"
        End If

        Dim s As String = ""

        While x <> 0UL
            If (x And 1UL) = 1UL Then
                s = "1" & s
            Else
                s = "0" & s
            End If
            x >>= 1
        End While

        Return s
    End Function

    ' Copy bits from M into N between bit positions [i, j]
    Function CopyBits(N As ULong, M As ULong, i As Integer, j As Integer) As ULong
        If i < 0 OrElse j < 0 OrElse i > j OrElse j >= 63 Then
            Throw New ArgumentException("Invalid bit range")
        End If

        Dim length As Integer = j - i + 1

        ' Mask for bits i..j
        Dim mask As ULong = ((1UL << length) - 1UL) << i

        ' Clear bits i..j in N
        Dim N_cleared As ULong = N And Not mask

        ' Take only the needed bits from M and shift into place
        Dim M_shifted As ULong = (M And ((1UL << length) - 1UL)) << i

        Return N_cleared Or M_shifted
    End Function

    Sub Main()

        '
        '   N:      100 011111 00
        '   M:          110011
        '   Result: 100 110011 00
        '

        Dim N As ULong = &B10001111100UL
        Dim M As ULong = &B110011UL

        Dim result As ULong = CopyBits(N, M, 2, 7)

        Console.WriteLine("N:      " & ToBinary(N))
        Console.WriteLine("M:      " & ToBinary(M))
        Console.WriteLine("Result: " & ToBinary(result))

    End Sub

End Module


'
' OUTPUT:
'
' N:      10001111100
' M:      110011
' Result: 10011001100
'

 



answered Mar 30 by avibootz

Related questions

...