Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write large 4 byte integer as an unsigned, binary

I have integers which floats between values: 4000000000-4294967000 (which is less than int max for a 4 byte unsigned int)

and i want to save it to file, and then re-read value

$f = fopen($fileName, 'wb'); fwrite($f, pack('I', $value));

It is important that in file, value must be exact 4 byte unsigned int, because external devices will expect that format of data. But PHP stores that big values as float, and destroys binary representation.

How i can write that numbers to file in that format?

[EDIT] @FractalizeR thx this works i have:

protected static function handleUint($direction, $value)
{
    if($direction == 'encode')
    {
        $first2bytes    = intval($value / (256 * 256));
        $second2bytes   = intval($value - $first2bytes);

        return pack('n2', $first2bytes, $second2bytes);
    }
    else
    {
        $arr = unpack('n2ints', $value);
        $value = $arr['ints1'] * (256 * 256) + intval($arr['ints2']) - 1;
        return $value;
    }
}

But i dont quite understand, why i have to -1 on the returning value, and is this binary will be produced correct?

like image 473
canni Avatar asked Nov 06 '22 09:11

canni


1 Answers

Well, split that 4 bytes number into 2 2-bytes numbers (integer divide by 256*256 to get the first word and subtract that value from original one to get the second one) and write in two packs.

like image 73
Vladislav Rastrusny Avatar answered Nov 10 '22 21:11

Vladislav Rastrusny