I was on MDN when I noticed that Chrome’s V8 (at least) was little-endian, meaning that a hexadecimal number you’d write as 0xCAFEBABE is actually stored as BE BA FE CA if you read the bytes off memory. It made me wonder how you could most easily determine if your system is little or big endian. I then came upon this gem:
echo -n I | od -to2 | head -n1 | cut -f2 -d" " | cut -c6
I’ll go through it part by part:
echo -n I– You’re already familiar withecho. The-nswitch just suppresses the newline\ncharacter that, by default, follows the output. This part just prints the letterI.od -to2– If you look atman ascii, you’ll notice that in the 7-bit octal range (00 to 0177), the letter I is 0111, which has the convenient property of being all 1’s.odis a program that lets you inspect, in human-readable format, what may or may not be printable characters. The-to2switch tells it to print 2 bytes in octal. (The-to1switch would not work because both little-endian and big-endian machines would indistinguishably print111.) Little-endian machines will give you0000000 000111while big-endian machines will give you0000000 111000. Great! Let’s simplify this result down a bit.head -n1– Here’s an easy one. We’re just grabbing the first line ofstdinand spitting it back out.cut -f2 -d" "– Another good one to know. Cut isstring.split(). The-f2switch tells it that the second field is desired, and the-d" "switch gives it a single space character as a delimeter.cut -c6– Finally, here’s another cut. This one just grabs the 6th character. The 4th or the 5th would also suffice.
You could take this one-liner a step further and add conditional printing of “big endian” or “little endian”, but by point #2, it’s pretty much there.