Tuesday, May 24, 2005

Bit Shifting in VB.NET

Here's a good tidbit of info from Scott Hanselman: "Machine.Shift.Left and Bit Shifting in VB.NET"

Haven't used bit shifting in a long while, but this info is pretty cool and goes back to BASICs...

(Thanks, Scott for the refresher on how to use VB! And yes, VB can be a bit too high level for some intense operations. Isn't that why MS created VS Studio?)

Here's a bit of code from NNTP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Function SafeLeftShift(ShiftThis As Integer, ShiftPlaces As Integer) As Integer
    Dim ShiftThisPrivate As Integer ' Private copy with extraneous bits unset
    Dim SignBitMask As Integer ' Mask for fixing msb

    ' Unset leftmost bits that will be discarded
    ShiftThisPrivate = ShiftThis And ((2 ^ (15 - ShiftPlaces)) - 1)

    ' Determine whether the sign bit should
    ' be set in the bit-shifted result
    If ShiftThis And (2 ^ (15 - ShiftPlaces)) Then
        SignBitMask = &H8000
    End If

    ' Do the bit shift.
    SafeLeftShift = (ShiftThisPrivate * (2 ^ ShiftPlaces)) Or SignBitMask
End Function

No comments: