Endianness

One thing I think is important that Bitcoin lacks is proper awareness of Endianness in its code. One thing we are taught as network programmers is that endianness matters and Bitcoin shows very little acknowledgement of it. Endianness to those unaware is the ordering of bytes in memory. Wikipedia has an article you can read if you are more interested. http://en.wikipedia.org/wiki/Endianness .

Networking for the most part is “big endian” which is the most logical ordering of bytes in memory. x86 and x64 CPUs on the other hand are “Little endian”. Core Bitcoin only works on “Little endian” machines because there is no code to make sure that if it is compiled on a “big endian” machine that it will switch the bytes around correctly.

I have structured MicroCash so that it will compile and work correctly on any CPU type, big or little endian. It is one advantage of having a thorough understanding of networking before starting a project. A smart way to do this in C or C++ is to have macros.

#ifdef MSB_CPU
#define MAKE_LE16(x) ENDIANSWAP_16(x)
#else
#define MAKE_LE16(x) (x)
#endif

The above code will swap the bytes around if used on a big endian CPU and do nothing if used on a little endian machine. So if we then wrap all appropriate networking code with it, it will automatically switch based on what is compiling it!

m_MSG_MAGIC = MAKE_LE16(m_MSG_MAGIC);
m_MSG_LEN = MAKE_LE16(m_MSG_LEN);

I favor little endian machines in MicroCash since that is the predominant CPU at the moment and it’s worth optimizing for that case. However in the future Big endian CPUs may become dominant and no one wants to have to recode the entire MicroCash to support such things.

Advertisements
%d bloggers like this: