Reading a signed 64 bit integer from a file with PHP

Posted by

This may be a ridiculous way to do this but I couldn’t think of anything better at the time of writing. The function takes in $db which is the handle to a file pointer resource (e.g. the return of an fopen() call) and returns the result as an int, or float if it overflows.

I basically read 2x 4 byte binary strings from the file and unpack them as unsigned 32 bit (big endianWikipedia: In computing, endianness is the order in which bytes within a word of digital data are transmitted over a data communication medium or addressed (by rising addresses) in computer memory, counting only...)  longs. I then check if it’s negative by checking if the first bit of the first 4 byte string is a 1 (using binary AND). I strip the sign bit (with binary AND again) and add the two numbers together – first shifting the first 4 bytes I read 32 bits to the left. I then re-sign the number if it was originally negative by multiplying it by -1. Finally I return the result.

Do feel free to leave a comment if you know a better way to do this. I’m all ears!

<?php
function read64_int($db) {
    $first = reset(unpack('N', fread($db, 4)));
    $second = reset(unpack('N', fread($db, 4)));

    // Get whether -ve (& 1000...)
    $negative = (bool)($first & pow(2, 31));

    // Strip the sign (& 0111...)
    $first &= (pow(2, 31) - 1);

    // Add the two
    $result = ($first << 32) + $second;

    // Make it -ve if we need to
    if ($negative)
        $result *= -1;

    // Return
    return $result;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *