note 112377 added to function.pack
| From: | SergeyKolomenkin | Date: | Sat, 08 Jun 2013 21:10:46 +0000 |
| Subject: | note 112377 added to function.pack | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195111@lists.php.net to get a copy of this message | ||
Useful function to swap bytes in long using pack/unpack:
<?php
function bswap($long)
{
// Convert long to 4-byte string in native byte order,
// unpack string to array with 4 elements (indices are started from 1 sic!):
$x = unpack("C4", pack("L", $long));
// Swap array elements and pack into 4-byte string,
// convert string to long in native byte order:
// PHP don't allow to use brackets ([]) after function call. So we need to use temp variable:
$x2 = unpack("L", pack("C4", $x[4], $x[3], $x[2], $x[1]));
return $x2[1];
}
?>
Unfortunatelly function can't be minified without using a lot of arithmetic and bit masks.
<?php
// SAMPLE USAGE:
$ip1 = '65.66.67.168';
$ip2 = long2ip(bswap(ip2long($ip1)));
echo "ip1 = $ip1\n";
echo "ip2 = $ip2\n";
// output:
// ip1 = 65.66.67.168
// ip2 = 168.67.66.65
?>
----
Server IP: 69.147.83.199
Probable Submitter: 78.129.223.36
----
Manual Page -- http://php.net/manual/en/function.pack.php
Edit -- https://master.php.net/note/edit/112377
Del: integrated -- https://master.php.net/note/delete/112377/integrated
Del: useless -- https://master.php.net/note/delete/112377/useless
Del: bad code -- https://master.php.net/note/delete/112377/bad+code
Del: spam -- https://master.php.net/note/delete/112377/spam
Del: non-english -- https://master.php.net/note/delete/112377/non-english
Del: in docs -- https://master.php.net/note/delete/112377/in+docs
Del: other reasons-- https://master.php.net/note/delete/112377
Reject -- https://master.php.net/note/reject/112377
Search -- https://master.php.net/manage/user-notes.php