herhor67 herhor67 - 30 days ago 16
PHP Question

Interpreting as unsigned 32 bit integer with PHP

I am trying to make little PHP tool for World of Tanks that will read battle replays.
You can see there what each replay consists of and there is an example.

Unfortunately I don't understand this part of wiki article:

Read 4 bytes, and interpret these as an unsigned 32 bit integer, let this be "block count"

I tried to convert their Java code to PHP, but it outputs "0" all the time.
Also I tried code found at php.net/manual/en/language.types.integer.php#38478 but it outputs "0" too.

Here is my current code:

function parse($string)
$x = (float)$string;
if ($x > (float)2147483647)
$x -= (float)"4294967296";
return (int)$x;

$replay = file_get_contents('steppes.txt');

$magic = substr($replay, 0, 4);
$count = substr($replay, 4, 4);

echo $magic." -- ".parse($magic)."<br>".$count." -- ".parse($count);

Answer Source

You can use the PHP-function unpack to convert binary data.

In your case you should use the code V which is for

unsigned long (always 32 bit, little endian byte order)

(long is a name used for a 32bit integer). You didn't specify the used byte-order, but looking at your demo-data I assume it is little endian. For a list of all 'codes', see the documentation of the pack-function.

$replay = file_get_contents('steppes.txt');
$info = unpack('Vmagic/Vcount', $replay);
echo 'Magic: ' . $info['magic'];
echo '<br/>';
echo 'Count: ' . $info['count'];