note 106041 added to function.unpack
| From: | rogier at osu1 dot php dot net | Date: | Wed, 05 Oct 2011 14:19:41 +0000 |
| Subject: | note 106041 added to function.unpack | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-183642@lists.php.net to get a copy of this message | ||
be aware of the behavior of your system that PHP resides on.
On x86, unpack MAY not yield the result you expect for UInt32
This is due to the internal nature of PHP, being that integers are internally stored as SIGNED!
For x86 systems, unpack('N', "\xff\xff\xff\xff") results in -1
For (most?) x64 systems, unpack('N', "\xff\xff\xff\xff") results in 4294967295.
This can be verified by checking the value of PHP_INT_SIZE.
If this value is 4, you have a PHP that internally stores 32-bit.
A value of 8 internally stores 64-bit.
To work around this 'problem', you can use the following code to avoid problems with
unpack.
The code is for big endian order but can easily be adjusted for little endian order (also, similar
code works for 64-bit integers):
<?
function _uint32be($bin)
{
// $bin is the binary 32-bit BE string that represents the integer
if (PHP_INT_SIZE <= 4){
list(,$h,$l) = unpack('n*', $bin);
return ($l + ($h*0x010000));
}
else{
list(,$int) = unpack('N', $bin);
return $int;
}
}
?>
Do note that you *could* also use sprintf('%u', $x) to show the unsigned real value.
Also note that (at least when PHP_INT_SIZE = 4) the result WILL be a float value when the input is
larger then 0x7fffffff (just check with gettype);
Hope this helps people.
----
Server IP: 91.199.167.223
Probable Submitter: 77.171.72.226
----
Manual Page -- http://www.php.net/manual/en/function.unpack.php
Edit -- https://master.php.net/note/edit/106041
Del: integrated -- https://master.php.net/note/delete/106041/integrated
Del: useless -- https://master.php.net/note/delete/106041/useless
Del: bad code -- https://master.php.net/note/delete/106041/bad+code
Del: spam -- https://master.php.net/note/delete/106041/spam
Del: non-english -- https://master.php.net/note/delete/106041/non-english
Del: in docs -- https://master.php.net/note/delete/106041/in+docs
Del: other reasons-- https://master.php.net/note/delete/106041
Reject -- https://master.php.net/note/reject/106041
Search -- https://master.php.net/manage/user-notes.php