Saad Saad - 8 days ago 5
PHP Question

Convert String in Host byte order (Little endian) to Network byte order (Big endian)

I have a Hex String which reads

18000000
this String is in Host byte order (Little endian) and I need to convert it to Network byte order (Big endian). The resultant Hex String will be
00000018
.

To summarize I need to convert
18000000 to 00000018


How do I achieve this in PHP?

Answer

You can use pack / unpack functions to convert endianness:

/**
 * Convert $endian hex string to specified $format
 * 
 * @param string $endian Endian HEX string
 * @param string $format Endian format: 'N' - big endian, 'V' - little endian
 * 
 * @return string 
 */
function formatEndian($endian, $format = 'N') {
    $endian = intval($endian, 16);      // convert string to hex
    $endian = pack('L', $endian);       // pack hex to binary sting (unsinged long, machine byte order)
    $endian = unpack($format, $endian); // convert binary sting to specified endian format

    return sprintf("%'.08x", $endian[1]); // return endian as a hex string (with padding zero)
}

$endian = '18000000';
$big    = formatEndian($endian, 'N'); // string "00000018"
$little = formatEndian($endian, 'V'); // string "18000000"

To learn more about pack format take a look at http://www.php.net/manual/en/function.pack.php

Comments