Results 1 to 14 of 14

Thread: >> and << functions for VB

Threaded View

  1. #1

    Thread Starter
    Head Hunted anhn's Avatar
    Join Date
    Aug 2007
    Location
    Australia
    Posts
    3,669

    >> and << functions for VB

    VB does not have >> and << operators but we can create functions to simulate them.
    Without unsign data type other than Byte, so we can use only 31 right bits of Long (the largest Long number is 2^31-1).
    (Notation "&" below denotes a Long number)

    Edit: See New version in post#7

    Code:
    Function RShift(Num as Long, b as Byte) As Long 
    '--- Num >> b
       If Num > 0 then
          If b < 31 then
             '-- shift to the right with 0's patched to the left
             RShift = Num \ (2& ^ b)
          Else
             RShift = 0 '-- all bits are shifted away
          End if
       ElseIf Num = 0 then
          RShift = 0
       Else
          '-- can raise an error here
          MsgBox "Num must be >= 0"
       End If
    End Function
    Code:
    Function LShift(Num as Long, b as Byte) As Long
    '-- Num << b
       If Num > 0 then
          If b = 0 then
             LShift = Num '-- shift nothing
          ElseIf b < 31 then
             '-- Num mod 2&^(31-b) will shift the left-most bits away first to avoid overflow.
             '    * (2& ^ b) will shift the remaining bits to the left 
             '               with 0's patched to the right.
             LShift = (Num mod 2&^(31-b)) * (2& ^ b)
          Else 
             LShift = 0 '-- all bits are shifted away
          End if
       ElseIf Num = 0 then
          LShift = 0
       Else
          '-- can raise an error here
          MsgBox "Num must be >= 0"
       End If
    End Function
    Last edited by anhn; Jun 19th, 2010 at 09:02 PM.
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • If your question was answered please use Thread Tools to mark your thread [RESOLVED]
    • Don't forget to RATE helpful posts

    • Baby Steps a guided tour
    • IsDigits() and IsNumber() functions • Wichmann-Hill Random() function • >> and << functions for VB • CopyFileByChunk

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width