C Programmers!!! Logical Shift

Discussion in 'OT Technology' started by Ben Fong-Torres, Jan 26, 2004.

  1. I need to write a function to do a logical right shift.
    So something like this:
    11111111000000001111111100000000
    could be shifted right 2 times and returned as
    00111111110000000011111111000000
     
  2. CyberBullets

    CyberBullets I reach to the sky, and call out your name. If I c

    Joined:
    Nov 13, 2001
    Messages:
    11,865
    Likes Received:
    0
    Location:
    BC, Canada/Stockholm, Sweden
    ummmmmm i can do it in assembly :)

    Code:
    mov ax, 0011111111000000b   ;this moves 3FC0
    sl ax, 1                                ;this is a logical shift left of 1.... 1 can be replaced with any number       
    sr ax, 1                                ;this is a logical shift right of 1.... 1 can be replaced with any number
    
    remember when shifting , the byte that is being shifted is going to the CB Flag (Carry Bit). :) hope that helps.
     
  3. skinjob

    skinjob Active Member

    Joined:
    Jan 6, 2001
    Messages:
    2,337
    Likes Received:
    0
    Location:
    Aztlán
    The shift operators in C/C++ are << for left-shift, and >> for right-shift. The operators take two arguments: the value to be shifted and the number of bits to shift.

    e.g. x = 4 << 2;

    This will take the value 4 and shift it 2 bits to the left and store the result in the variable x.

    On a right shift, if the value being shifted is unsigned, the vacated bits will be filled in with 0's. If the value is signed and negative, the vacated bits will be filled in with 1's.
     
  4. What if I want the vacated bits to be filled with 0's no matter what?
     
  5. skinjob

    skinjob Active Member

    Joined:
    Jan 6, 2001
    Messages:
    2,337
    Likes Received:
    0
    Location:
    Aztlán
    declare your function argument as unsigned, or just mask them out.
     

Share This Page