Jesse
Jesse

Reputation: 76

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

Upvotes: 2

Views: 2948

Answers (2)

avpaderno
avpaderno

Reputation: 29689

To change endianness for an hexadecimal string that could contain spaces, I would use the following code.

function change_endianness(string $input): string {
  $input = str_replace(' ', '', $input);
  $output = unpack("H*", strrev(pack("H*", $input)))[1];
  // Add a space every two hexadecimal digits.
  $output = implode(' ', str_split($output, 2));
  // Convert lowercase hexadecimal digits to uppercase.
  return strtoupper($output);
}
echo change_endianness('E1 31 3C 01 00 00 9B'), "\n";
9B 00 00 01 3C 31 E1

Upvotes: 0

maxhb
maxhb

Reputation: 8865

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

Upvotes: 6

Related Questions