Fastest way to split a word into two bytes

Jonas picture Jonas · Jul 25, 2013 · Viewed 6.9k times · Source

So what is the fastest way to split a word into two bytes ?

short s = 0x3210;
char c1 = s >> 8;
char c2 = s & 0x00ff;

versus

short s = 0x3210;
char c1 = s >> 8;
char c2 = (s << 8) >> 8;

Edit

How about

short s = 0x3210;
char* c = (char*)&s; // where c1 = c[0] and c2 = c[1]

Answer

iammilind picture iammilind · Jul 25, 2013

Let the compiler do this work for you. Use union, where the bytes will be split without any hand made bit-shifts. Look at the pseudo code:

union U {
  short s;  // or use int16_t to be more specific
  //   vs.
  struct Byte {
    char c1, c2;  // or use int8_t to be more specific
  }
  byte;
};

Usage is simple:

U u;
u.s = 0x3210;
std::cout << u.byte.c1 << " and " << u.byte.c2;

The concept is simple, afterwards you can overload the operators to make it more fancy if you want.

Important to note that depending on your compiler the order of c1 and c2 may differ, but that will be known before the compilation. You can set some conditinal macros to make sure that order is according to your needs in any compiler.