FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » signed int64 pack/unpack
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: signed int64 pack/unpack [message #184590 is a reply to message #184579] Sun, 12 January 2014 05:54 Go to previous messageGo to previous message
cameron7 is currently offline  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);
}
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: how did I wind up with double headers?
Next Topic: Switch question
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Mon Nov 25 00:09:28 GMT 2024

Total time taken to generate the page: 0.04473 seconds