Bash (and other unix shells), 32 (33) bytes
First and second attempt:
case `echo|od` in *5*)echo B;;*)echo L;;esac # portable
[[ `echo|od` =~ 5 ]]&&echo B||echo L # non-portable
Thanks to Dennis, shorter version:
od<<<a|grep -q 5&&echo L||echo B # non-portable
echo|od|grep -q 5&&echo B||echo L # portable
The echo
utility outputs a newline, with hex value 0A
, and no other output. For <<<a
it is 61 0A
.
The od
utility, by default, interprets the input as two-byte words, zero-padded if the number of bytes is odd, and converts to octal. This results in the output of echo being interpred as 0A 00
, which is converted to 005000
as big-endian or 000012
in little-endian. 61 0A
becomes 005141
in little-endian and 060412
in big-endian. The full output of od also includes address and size data meaning we cannot use 0
, 1
, or 2
for the test.
The command is well-defined to expose the system's endianness. From the standard:
The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system.
Compatibility notes
I am not certain if putting echo|od
in backquotes with no double quotes around them [which results in a three-word argument to case
] is supported on all systems. I am not certain if all systems support shell scripts with no terminating newline. I am mostly certain but not 100% of the behavior of od with adding the padding byte on big-endian systems. If needed, echo a
can be used for the portable versions. All of the scripts work in bash, ksh, and zsh, and the portable ones work in dash.
B0 4C C3
, which ismov al, 'L' / ret
orunsigned char f(){ return 'L'; }
, would be a valid x86 answer. \$\endgroup\$