Convert Little endian to Big endian in PHP or vice versa

In PHP you might have to convert the endianness of a number. PHP does not provide any function for this even though it has function for almost everything.

So I wrote a function for this,

[code language=”php”]
function chbo($num) {
$data = dechex($num);
if (strlen($data) <= 2) {
return $num;
}
$u = unpack("H*", strrev(pack("H*", $data)));
$f = hexdec($u[1]);
return $f;
}[/code]

Usage:

php > echo var_dump(5254071951610216, chbo(5254071951610216448));
int(5254071951610216)
int(20120214104648)
php > echo var_dump(2147483648, chbo(2147483648));
int(2147483648)
int(128)

Note: this function changes the byte order. If your machines byte-order is little-endian, this function will change it to big-endian. If your machines byte-order is big-endian, it will change the number to big-endian.

All x86 and x86_64 are little-endian. ARM can be both.  More can be found on this wiki article

One thought on “Convert Little endian to Big endian in PHP or vice versa

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve * Time limit is exhausted. Please reload the CAPTCHA.