Quick tip: Byte order of your system

Byte Order! Well, this is one thing many of us have kinda forgotten and/or don’t bother. Well, after all this is more on how the hardware works and not on how the software is written. Of course, this needs to be taken into consideration in network programming as well but again not so much in detail.

Anyways, today I faced with a task of finding the byte order (aka Endianness) of a embedded box to which I had a very basic shell interface through COM Port (aka serial port). So, in other words, I am limited by what I have, which is just a shell. So, no ‘C’ code or anything is possible. Like all of us I googled for it & found this brilliant discussion on how to do this in various languages like python, perl, etc… Guess what, I don’t even have ‘od’ on my box!!!

So, here is my solution.

Big Endian
$ echo -n I | hexdump -o | head -n1 | awk '{print $2}' | cut -c6
0
Little Endian
$ echo -n I | hexdump -o | head -n1 | awk '{print $2}' | cut -c6
1

Simple, isn’t it? Well, here is the break up & explanation.

Break up of the command
  • echo -n I                 print the character ‘I’
  • hexdump -o            2 byte octal display
  • head n1                  print only one line
  • awk ‘{print $2}’        print the 2nd field (by default, separated by space)
  • cut -c6                    6th character
Explanation

Well this is kinda straight forward. ASCII value for I is 73 (in decimal) or 0x49 (in hex) or 111 (in octal). So, if I dump the hex value of the ASCII value for ‘I’ in Little Endian it should be 0049 but on the Big Endian it should be 4900! Check it here:

Little Endian box (Hex format)
$ echo -n I | hexdump
0000000 0049
0000001
Big Endian embedded box (Hex format)
# echo -n I | hexdump
0000000 4900
0000001

But, we use the octal representation so that it is easier to automate it. So, here it is in octal format:

Little Endian box (Octal format)
$ echo -n I | hexdump -o
0000000 000111
0000001
Big Endian embedded box (Octal format)
# echo -n I | hexdump -o
0000000 044400
0000001

Well, you see the difference now? If you look it these are strings, then the last character of the response is ‘1’ in case of Little Endian and ‘0’ in case of Big Endian. So when trying to figure it out programmatically we can look for the last character of the output.

Simple, yeah? 🙂

No Comments

Post a Comment

%d bloggers like this: