note 63399 deleted from function.pack by nlopess
| From: | nlopess@php.net | Date: | Wed, 22 Mar 2006 09:42:23 +0000 |
| Subject: | note 63399 deleted from function.pack by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-106220@lists.php.net to get a copy of this message | ||
Note Submitter: noah dot medling at gmail dot com
----
Here's a function I wrote to flip between big- and little endian byte order, but only on
systems that use little endian; it doesn't do anything on big endian systems:
<?php
function flip($data){
// do nothing on big-endian systems
if(pack('S', 0x1234) !== pack('v', 0x1234)) return $data;
// append a NUL byte to odd-length strings
if(($n = strlen($data)) % 2 === 1){
++$n;
$data .= chr(0);
}
// flip each pair of bytes
for($i = 0; $i < $n; $i += 2){
$c = $data{$i};
$data{$i} = $data{$i + 1};
$data{$i + 1} = $c;
}
return $data;
}
?>
You can use it to read and write signed values in big-endian format on any machine like this:
<?php
$unpacked = 0x12345678;
// pack a 32-bit signed integer, then force it to be big endian
$packed = flip(pack('l', $value));
// unpack the value:
$unpacked = flip(unpack('l', $value));
?>
If you prefer to force little endianness instead of what I've got here, all you have to do is
change the !== to === in that first if statement.