6

In C# I can get the endianness type by this code snippet:

if(BitConverter.IsLittleEndian)
{
   // little-endian is used   
}
else
{
   // big-endian is used
}

How can I do the same in PHP?

4
  • Detect the endianness of what specifically?
    – webbiedave
    Mar 16, 2012 at 22:00
  • 2
    For example when using socket_send($socket, $data, $len). Which endianness is used?
    – HomeCoder
    Mar 16, 2012 at 22:04
  • $data is an 8-bit binary string, a char sequence (like all php strings). It has no endianness. If you need to prepare binary data in a specific endianness, use the pack() and unpack() functions. Mar 16, 2012 at 22:08
  • 3
    If you want to get the current machine endian order, you can use pack() with the format option l or L and a constant input and evaluate the result.
    – Niko
    Mar 16, 2012 at 22:14

2 Answers 2

12

PHP's string type is an 8-bit binary string, a char sequence. It has no endianness. Thus for the most part endianness is a non-issue in PHP.

If you need to prepare binary data in a specific endianness, use the pack() and unpack() functions.

If you need to determine the machine's native endianness, you can use pack() and unpack() in the same way.

function isLittleEndian() {
    $testint = 0x00FF;
    $p = pack('S', $testint);
    return $testint===current(unpack('v', $p));
}
3
  • 1
    Thanks for your answer. So, where can I find a machine which returns false? :-)
    – HomeCoder
    Mar 16, 2012 at 22:33
  • 2
    A PowerPC should return false. If you never run on bigendian machines, why ask the question? Mar 16, 2012 at 22:57
  • 2
    Because I don't know exaclty what machines my clients are using.
    – HomeCoder
    Mar 16, 2012 at 23:08
8
function isLittleEndian() {
    return unpack('S',"\x01\x00")[1] === 1;
}

Little-endian systems store the least significant byte in the smallest (left-most) address. Thus the value 1, packed as a "short" (2-byte integer) should have its value stored in the left byte, whereas a big-endian system would store it in the right byte.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.