[UPD] bitwise "shift"s

Sean Shao shaosean at hotmail.com
Fri Nov 25 05:22:37 EST 2005


Sorry for the post earlier, but it seems that there's a small error in it.. 
Here are the 3 fixed bitwise shift operators (shiftLeft (<<), shiftRight 
(>>) and shiftRightZero (>>>)).. Basically there are some integer 
combinations that would make the other formulas fail and sometimes the 
shiftRightZero would return a negative integer (which is impossible).. So 
here are the three corrected functions:

function bitwiseShiftLeft p1, p2
  local tP1Neg
  put (p2 MOD 32) into p2
  if (p1 < 0) then put TRUE into tP1Neg
  if (p2 = 0) then return p1
  put baseConvert(p1, 10, 2) into p1
  repeat p2
    put 0 after p1
  end repeat
  if (tP1Neg) then return 0 - baseConvert(char -32 to -1 of p1, 2, 10)
  else return baseConvert(char -32 to -1 of p1, 2, 10)
end bitwiseShiftLeft

function bitwiseShiftRight p1, p2
  local tP1Neg, tPad
  put (p2 MOD 32) into p2
  if (p2 = 0) then return p1
  if (p1 > 0) then return trunc(p1 / (2 ^ p2))

  if (abs(p1) = (2^p2)) then return trunc(p1 / (2^ p2))
  else return trunc(p1 / (2 ^ p2)) -1
end bitwiseShiftRight

function bitwiseShiftRightZero p1, p2
  put (p2 MOD 32) into p2
  if (p1 > 0) then return trunc(p1 / (2 ^ p2))
  #if (p2 = 0) then return p1
  if (p1 < 0) then
    put baseConvert(bitNot abs(p1) +1, 10, 2) into p1
    repeat p2
      delete char -1 of p1
      put 0 before p1
    end repeat
    return abs(baseConvert(p1, 2, 10))
  end if
end bitwiseShiftRightZero

_________________________________________________________________
On the road to retirement? Check out MSN Life Events for advice on how to 
get there! http://lifeevents.msn.com/category.aspx?cid=Retirement




More information about the use-livecode mailing list