Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pack and unpack 64 bit integer

Tags:

php

I have the following code:

$packed = pack('i',PHP_INT_MAX);
echo unpack('i', $packed)[1];

As result I get -1

I'm using PHP 5.4.6-1ubuntu1.1 (cli) (built: Nov 15 2012 01:18:34) and my PHP_INT_MAx is equal to 9223372036854775807

Is there any way to work with pack function and 64 bit integers?

like image 831
Ris90 Avatar asked Jan 18 '13 19:01

Ris90


1 Answers

Save it as two 32Bit instead:

$value = PHP_INT_MAX;
$highMap = 0xffffffff00000000; 
$lowMap = 0x00000000ffffffff; 
$higher = ($value & $highMap) >>32; 
$lower = $value & $lowMap; 
$packed = pack('NN', $higher, $lower); 

list($higher, $lower) = array_values(unpack('N2', $packed)); 
$originalValue = $higher << 32 | $lower; 
  • Algorithm taken from: http://php.net/pack#109328
  • Example: http://codepad.viper-7.com/UuLmor
like image 83
KingCrunch Avatar answered Nov 17 '22 02:11

KingCrunch