PHP 32-bit Left Shift Function

PHP:
  1. function leftshift32($number, $steps)
  2. {
  3.     // convert to binary (string)
  4.     $binary = decbin($number);
  5.     // left-pad with 0's if necessary
  6.     $binary = str_pad($binary, 32, "0", STR_PAD_LEFT);
  7.     // left shift manually
  8.     $binary = $binary.str_repeat("0", $steps);
  9.     // get the last 32 bits
  10.     $binary = substr($binary, strlen($binary) - 32);
  11.     // if it's a negative number return the 2's complement
  12.     // otherwise just return the number
  13.     if ($binary{0} == "1")
  14.     {
  15.         return -(pow(2, 31) - bindec(substr($binary, 1)));
  16.     }
  17.     else
  18.     {
  19.         return bindec($binary);
  20.     }
  21. }

16 November 2006 | Software engineering, PHP | Comments

Comments:

  1.  
  2.  
  3.