Wednesday 14 March 2012

VB6 Bit Shifting

Function ShiftRight(ByVal lngNumber as Long, ByVal intNumBits as Integer) as Long
'--------------
'BIT SHIFT RIGHT
'--------------

ShiftRight = lngNumber \ 2^intNumBits 'note the integer division op

End Function




Function ShiftLeft(Byval lngNumber as Long, ByVal intNumBits as integer) as Long
'--------------
'BIT SHIFT LEFT
'--------------

ShiftLeft = lngNumber * 2^intNumBits

End Function

5 comments:

  1. Sory, this may be will not work for minus. for example if the long value is &HFFFFFFFF, the last is &H80000000, if continue will overflow.

    If the content is &H8FFFFFFF then this can't be shift at all.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Function LeftBitWise(ByVal SrcValue As Variant, ByVal Times As Byte) As Variant
    Dim SrcStr As String
    Dim myValue As Long
    If Not IsNumeric(SrcValue) Then
    Exit Function
    End If

    myValue = CLng("&H" & Right("00000000" & Hex(SrcValue), 8))
    For a = 1 To Times
    myValue = myValue And &H7FFFFFFF
    If (&H40000000 And myValue) = &H40000000 Then
    myValue = (&H3FFFFFFF And myValue) * 2 Or &H80000000
    Else
    myValue = myValue * 2
    End If
    Next a

    LeftBitWise = Right("00000000" & Hex(myValue), 8)

    If VarType(SrcValue) = vbByte Then
    LeftBitWise = CByte("&H" & Right(LeftBitWise, 2))
    End If
    If VarType(SrcValue) = vbInteger Then
    LeftBitWise = CInt("&H" & Right(LeftBitWise, 4))
    End If
    If VarType(SrcValue) = vbLong Then
    LeftBitWise = CLng("&H" & Right(LeftBitWise, 8))
    End If
    End Function



    Private Sub Command1_Click()
    MsgBox Hex(LeftBitWise(CByte(&H1F), 8))
    MsgBox Hex(LeftBitWise(CInt(&HFFFF), 8))
    MsgBox Hex(LeftBitWise(CLng(&H8F1FFFFF), 8))
    End Sub

    ReplyDelete
  5. Bless you, Jamil! I've been scratching my head for a few hours trying to figure out how to do this in a nice way.

    ReplyDelete