C -> PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

_Thndr wrote:@feyd: Wow that did the trick! I did have to remove the '0' from the bcmod function, because it only seemed to take two arguments. Thanks a lot!
Yeah, sorry about that.. I adjusted the code without checking it from the one I wrote on my dev box.

bcmath is used for arbitrary, often well beyond standard integer limits. You can, for instance keep precision of several hundred decimal places or add up numbers that go well beyond 2^32.

Here's the original I wrote:

Code: Select all

function getUserId($str)
{
	$x = '0';
	$user = strval($str);
	$j = strlen($user);
	bcscale(0);
	$keep = bcpow('2', '32');
	
	for ($i = 0; $i < $j; ++$i)
	{
		$x = bcmul($x, '101');
		$x = bcmod($x, $keep);
		$x = bcadd($x, ord(strtolower($user[$i])));
	}
	return $x;
}
Last edited by feyd on Fri Jun 23, 2006 12:37 pm, edited 1 time in total.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

yup, it returned the correct result for that sample data... but few more characters will break the algorithm. Basically, anything that transforms into userId > PHP_INT_MAX will yield wrong results.
Post Reply