note 63399 added to function.pack

From: Date: Wed, 22 Mar 2006 02:39:35 +0000
Subject: note 63399 added to function.pack
Groups: php.notes 
Request: Send a blank email to php-notes+get-106193@lists.php.net to get a copy of this message
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. ---- Server IP: 216.194.113.175 Probable Submitter: 12.207.80.29 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.pack.php Edit -- http://master.php.net/note/edit/63399 Del: integrated -- http://master.php.net/note/delete/63399/integrated Del: useless -- http://master.php.net/note/delete/63399/useless Del: bad code -- http://master.php.net/note/delete/63399/bad+code Del: spam -- http://master.php.net/note/delete/63399/spam Del: non-english -- http://master.php.net/note/delete/63399/non-english Del: in docs -- http://master.php.net/note/delete/63399/in+docs Del: other reasons-- http://master.php.net/note/delete/63399 Reject -- http://master.php.net/note/reject/63399 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#106193) next »