12

Is there an option to find if my system is little endian byte order or big endian byte order using Perl?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
oren
  • 479
  • 1
  • 6
  • 10

2 Answers2

21
perl -MConfig -e 'print "$Config{byteorder}\n";'

See Perl documentation.

If the first byte of the output string is 1, you can assume (with moderate safety) that it is little-endian. If it is 4 or 8, you can assume big-endian.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    +1 This is clearly the "right" way to do it. The other way is (while intuitive) just hacky. :-P – C. K. Young Apr 09 '10 at 21:04
  • True, although to get a boolean answer to the question "is this system big/little-endian?" you'd need to do further analysis on the value returned by the Config module. – Sean Apr 09 '10 at 21:16
  • 3
    @Sean: the trouble is (as the referenced documentation points out), the answer isn't binary - there is also 'weird' order (in theory) for machines like PDP-11 which use '3412' as the byte order - which is neither big-endian nor little-endian. If the first byte is 1, you can assume (with moderate safety) that it is little endian; if it is 4 or 8, you can assume big endian; and if it is none of these, then maybe it is time to get a newer machine. – Jonathan Leffler Apr 09 '10 at 21:34
4

I guess you could do:

$big_endian = pack("L", 1) eq pack("N", 1);

This might fail if your system has a nonstandard (neither big-endian nor little-endian) byte ordering (eg PDP-11).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sean
  • 29,130
  • 4
  • 80
  • 105
  • That was going to be my suggestion as well. :) Except I would use something with more bits filled than just binary 1. – Axeman Apr 09 '10 at 21:02