Bit Manipulation



  • Found this in some third-party code I've been asked to maintain:

    Public Shared Function GetBitNr(ByVal TestInteger As Integer, ByVal Nr As Integer) As Integer
       If TestInteger < 0 Then
          If Nr = 32 Then
             Return 1
          End If
          
          TestInteger = TestInteger + CInt(&H80000000)
       End If
       
       Dim i As Long = 30
       Dim str As String = ""
       Do While (i > -1)
          If 2 ^ i <= TestInteger Then
             str = str & "1"
             TestInteger = CInt(Math.Round(TestInteger - 2 ^ i))
          ElseIf Left(str, 1) = "1" Then
             str = str & "0"
          End If
          
          i = i - 1
       Loop
       
       Dim result As Integer
       If Len(str) >= Nr Then
          result = CInt(Mid(str, Len(str) - Nr + 1, 1))
       Else
          result = 0
       End If
       
       Return CInt(result)
    End Function

     

    Because testing whether a bit is set is so difficult!



  • Far future biologists will use this as evidence that humans had been evolving into two separate species:

    Those who can see that using Math.Round for bit calculations makes perfect sense, and those who can't.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.