note 100548 added to function.unpack
| From: | zac at picolink dot net | Date: | Fri, 22 Oct 2010 15:33:30 +0000 |
| Subject: | note 100548 added to function.unpack | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-173378@lists.php.net to get a copy of this message | ||
The documentation is clear that an integer read using an unsigned format character will still be
stored as a signed integer. The often-cited work-around is to use sprintf('%u', $bigint)
to properly display integers with the MSB set.
In the case where the numeric value is more important than how it's displayed, you can still
work with other large integers using intval() to "upgrade" your existing unsigned
integers.
I had a problem comparing 32-bit integers read from files with hard-coded constants (file signatures
tend to need this). Here's what I did to avoid converting everything into strings:
<?php
$bigint = 0x89504E47;
$packed = pack('N', $bigint);
list($unpacked) = array_values(unpack('N', $packed));
//The $bigint remains an unsigned integer.
//Even though their bit-wise values are identical, comparison fails.
echo 'bigint ',
($bigint == $unpacked ? '==' : '!='),
" unpacked\n";
//intval() triggers a re-interpretation of $bigint.
//$bigint is internally compared as a signed integer.
//Since the bit-wise value of $bigint never changes, comparison succeeds.
echo 'intval(bigint) ',
(intval($bigint) == $unpacked ? '==' : '!='),
" unpacked\n";
?>
It works, but it's a little backwards. If anyone has any ideas on how to "downgrade"
a signed integer into an unsigned integer without using strings, that would be a valuable note to
add to the documentation.
----
Server IP: 208.69.120.55
Probable Submitter: 76.212.32.90
----
Manual Page -- http://www.php.net/manual/en/function.unpack.php
Edit -- https://master.php.net/note/edit/100548
Del: integrated -- https://master.php.net/note/delete/100548/integrated
Del: useless -- https://master.php.net/note/delete/100548/useless
Del: bad code -- https://master.php.net/note/delete/100548/bad+code
Del: spam -- https://master.php.net/note/delete/100548/spam
Del: non-english -- https://master.php.net/note/delete/100548/non-english
Del: in docs -- https://master.php.net/note/delete/100548/in+docs
Del: other reasons-- https://master.php.net/note/delete/100548
Reject -- https://master.php.net/note/reject/100548
Search -- https://master.php.net/manage/user-notes.php