phpbyteendiannesspackunpack

PHP - convert little endian hex to big endian hex


I am trying to convert little endian hex to big endian hex.

Example:

Little endian: E1 31 01 00 00 9D

Big endian: 9D 00 00 01 31 E1


Solution

  • If numbers are in the format described than you can convert by using standard array functions.

    function littleToBigEndian($little) {
      return implode(' ',array_reverse(explode(' ', $little)));
    }
    
    echo littleToBigEndian('E1 31 3C 01 00 00 9B');
    // Output: 9B 00 00 01 3C 31 E1
    

    If there are no spaces for separation of numbers you need to str_split() the string instead.

    function littleToBigEndian($little) {
      return implode('',array_reverse(str_split($little,2)));
    }
    
    echo littleToBigEndian('E1313C0100009B');
    // Output: 9B0000013C31E1