How to check whether only 2 bits in a number at a specific position are on (edge‑case‑safe) with VB.NET

1 Answer

0 votes
Imports System

Module ExactTwoBits

	Sub PrintBits(value As ULong, width As Integer)
		Dim s As String = Convert.ToString(CLng(value), 2)  ' Convert to binary string
		Console.Write(s.PadLeft(width, "0"c))               ' Pad with leading zeros
	End Sub


    '
    ' exactBitSet:
    ' ------------
    ' Returns True only if:
    '
    '   • pos1 and pos2 are valid (>= 0, < 64, and not equal)
    '   • value has EXACTLY those two bits set
    '   • all other bits are OFF
    '
    ' Bit positions are ZERO‑BASED from the RIGHT (LSB = position 0).
    '
    Function ExactBitSet(pos1 As Integer, pos2 As Integer, value As ULong) As Boolean
        If pos1 < 0 OrElse pos2 < 0 OrElse pos1 >= 64 OrElse pos2 >= 64 Then
            Return False
        End If

        If pos1 = pos2 Then
            Return False
        End If

        Dim mask As ULong = (1UL << pos1) Or (1UL << pos2)
        Return value = mask
    End Function

    Structure Test
        Public value As ULong
        Public x As Integer
        Public y As Integer
        Public width As Integer
    End Structure

    Sub Main()

        Dim tests() As Test = {
            New Test With {.value = &B1000010000UL, .x = 4, .y = 9, .width = 10},
            New Test With {.value = &B0010000010UL, .x = 1, .y = 7, .width = 10},
            New Test With {.value = &B0000100100UL, .x = 2, .y = 5, .width = 10},
            New Test With {.value = &B1000010000UL, .x = 3, .y = 9, .width = 10},
            New Test With {.value = &B1001010000UL, .x = 4, .y = 9, .width = 10},
            New Test With {.value = &B1111111111UL, .x = 4, .y = 9, .width = 10},
            New Test With {.value = &B0000000000UL, .x = 4, .y = 9, .width = 10},
            New Test With {.value = &B1000010000UL, .x = 4, .y = 8, .width = 10},
            New Test With {.value = 1UL, .x = 0, .y = 0, .width = 1},
            New Test With {.value = 1UL, .x = 0, .y = 1, .width = 1},
            New Test With {.value = 0UL, .x = 1, .y = 1, .width = 1}
        }

        For Each t In tests
            PrintBits(t.value, t.width)
            Console.Write("  bits(" & t.x & ", " & t.y & ")  ->  ")
            Console.WriteLine(If(ExactBitSet(t.x, t.y, t.value), "true", "false"))
        Next

    End Sub

End Module

										
'
' OUTPUT:
'
' 1000010000  bits(4, 9)  ->  true
' 0010000010  bits(1, 7)  ->  true
' 0000100100  bits(2, 5)  ->  true
' 1000010000  bits(3, 9)  ->  false
' 1001010000  bits(4, 9)  ->  false
' 1111111111  bits(4, 9)  ->  false
' 0000000000  bits(4, 9)  ->  false
' 1000010000  bits(4, 8)  ->  false
' 1  bits(0, 0)  ->  false
' 1  bits(0, 1)  ->  false
' 0  bits(1, 1)  ->  false
'

 



answered Apr 3 by avibootz
edited Apr 3 by avibootz

Related questions

...