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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s