Saad Saad - 1 year ago 84
PHP Question

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

I have a Hex String which reads

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

To summarize I need to convert
18000000 to 00000018

How do I achieve this in PHP?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download