View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.programming
TheWizEd TheWizEd is offline
external usenet poster
 
Posts: 8
Default Bitwise shift in VBA

My overflow was caused by saving the results to the wrong data type.

Multiplying and dividing by 2s works thanks.

"Chip Pearson" wrote:

The following code illustrates bit and byte shifts to the left or to
the right:

Sub AAA()
Dim L As Long
Dim K As Long
Dim BytesToShift As Long
Dim BitsToShift As Long

L = &H800 ' Test Value

' BytesToShift 0 -- shift left
' BytesToShift < 0 -- shift right
BytesToShift = 2
K = L * (&H10 ^ BytesToShift)
Debug.Print Hex(L), Hex(K)

L = &H80 ' Test Value
' BitsToShift 0 -- shift left
' BitsToShift < 0 -- shift right
BitsToShift = 2
K = L * (2 ^ BitsToShift)
Debug.Print Hex(L), Hex(K)
End Sub

You can wrap it all up in a single function to handle either bit or
byte shifts in either direction.

Function Shift(InL As Long, N As Long, _
Optional Bits As Boolean = False) As Long
Dim L As Long
If Bits = False Then
Shift = InL * (&H10 ^ N)
Else
Shift = InL * (2 ^ N)
End If
End Function

Cordially,
Chip Pearson
Microsoft Most Valuable Professional
Excel Product Group, 1998 - 2009
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)





On Mon, 7 Sep 2009 07:16:01 -0700, TheWizEd
wrote:

How do you perform a bitwise shift in VBA (Excel)?

I have seen an operator in some VB code like this.

x = y << 8 ' I believe this mean shift y 8 bits to the right

But this is not in VBA. Any suggestions?