Bit Shifting

Public Function LShift16(w As Integer, c As Integer) As Integer
    'Bitwise left shift for short integers.
    'Equal to C '<<' operator
    LShift16 = w * (2 ^ c)
End Function
Public Function RShift16(w As Integer, c As Integer) As Integer
    'Bitwise right shift for short integers.
    'Equal to C '>>' operator
    RShift16 = w \ (2 ^ c)
End Function

Usage example

Public Sub Foo()
Dim iVal as integer
    iVal = &HA0            '10100000
    iVal = RShift16(iVal, 4)
    Debug.Print iVal 'Now it's 00001010
End Sub

A word of caution: Right shifting minus one (-1) will always result in minus one. This is because the sign bit is not changed with bit-wise operations.

 

Tip Submitted By: Robert Stites