tags:

views:

40

answers:

1

Hello,

I have a simple function that I'm using but for some reason the number doesn't calculate correctly as it would in a calculator. I think it has something to do with the numbers being too large, or something to do with 64 bit. Is there any way I can convert them so that they would work correctly?

$sSteamComID = 76561197990369545;
$steamBase = 76561197960265728;

function convertToSteamID($sSteamComID) {
    $sServer = bcmod($sSteamComID, '2') == '0' ? '0' : '1';
 $sCommID = bcsub($sSteamComID, $sServer);
 $sCommID = bcsub($sCommID, $steamBase);
 $sAuth = bcdiv($sCommID, '2');

 echo "$sServer:$sAuth";
}

convertToSteamID($sSteamComID);

This function outputs 0:15051912 on a server when it should be printing 1:15051908

+1  A: 

The missing global $steamBase was the problem, as already mentioned in a comment. (Tip: turn on E_NOTICE during development.) However, I'd like to address your question:

I think it has something to do with the numbers being too large, or something to do with 64 bit. Is there any way I can convert them so that they would work correctly?

PHP integers are signed and platform-dependent. Using 64-bit numbers will not work if you are on a 32-bit host.

So your concern is valid. But even on a 64-bit system:

$x = 9223372036854775808; // highest bit (64th) set
var_dump($x);

--> float(9.2233720368548E+18)

Note that PHP's BC Math routines operate on strings, not integers. Thus, you should be storing your big numbers as strings.

This will work around the potential problem of integers being converted to floats, which will happen even on your 64-bit environment if you are using large, unsigned integers.

konforce