PHP 32-bit Left Shift Function

function leftshift32($number, $steps)
{
	// convert to binary (string)
	$binary = decbin($number);
	// left-pad with 0's if necessary
	$binary = str_pad($binary, 32, "0", STR_PAD_LEFT);
	// left shift manually
	$binary = $binary . str_repeat("0", $steps);
	// get the last 32 bits
	$binary = substr($binary, strlen($binary) - 32);
	// if it's a negative number return the 2's complement
	// otherwise just return the number
	if ($binary{0} == "1")
	{
		return -(pow(2, 31) - bindec(substr($binary, 1)));
	}
	else
	{
		return bindec($binary);
	}
}

16 November 2006 | Software engineering, PHP | Comments

3 Responses to “PHP 32-bit Left Shift Function”

  1. 1 David 7 October 2008 @ 1:51 am

    Very useful, thanks! Struggled for hours today with PHP’s integer add / lshift / rshift while translating some otherwise very simple C code to PHP.

  2. 2 Rizal 8 October 2008 @ 9:53 am

    You’re welcome David! Glad you found it useful.

  3. 3 Adam H 10 October 2008 @ 10:51 pm

    This function doesn’t output the correct value if the $steps is 32. And that’s what I needed hrm.

Comments:

  1.  
  2.  
  3.