Re: signed int64 pack/unpack [message #184590 is a reply to message #184579] |
Sun, 12 January 2014 05:54 |
cameron7
Messages: 8 Registered: January 2014
Karma:
|
Junior Member |
|
|
Ok, so here's some code where we can start from:
This is giving me:
OUTPUT:
------------
PACKING: 8223372036854775807
UNPACKED: 8223372036854775807
However, when we're dealing with negative numbers:
OUTPUT:
------------
PACKING: -8223372036854775807
UNPACKED: 10223372036854776028
This likely will simply require some experimentation, for example I'm using "unsigned" flags to unpack, but it's not obvious, since when I go with a "signed" flag for negative values (ie. 'l' for signed long) I'm getting the same. If someone on the list has experience hacking binary protocols in PHP would love to know if there's a better way...
<?php
$i64 = 8223372036854775807;
echo "PACKING: ".$i64.PHP_EOL;
$binary = getBinaryString($i64, 64);
list(,$i64a) = unpack('N', pack('N', base_convert(substr($binary, 0, 32), 2, 10)));
list(,$i64b) = unpack('N', pack('N', base_convert(substr($binary, 32, 32), 2, 10)));
$i64c = getBinaryString($i64a, 32);
$i64d = getBinaryString($i64b, 32);
echo "UNPACKED: ".base_convert($i64c.$i64d,2,10).PHP_EOL;
function getBinaryString($packed,$bits){
$a = 0x01;
$binary = '';
for($x=0; $x<$bits; $x++){
$binary .= (int)(bool)($a & $packed);
$a = $a << 1;
}
return strrev($binary);
}
|
|
|