c++ - Fastest way to split a word into two bytes -
so fastest way split word 2 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; // c1 = c[0] , c2 = c[1]
let compiler work you. use union
, bytes split without hand made bit-shifts. @ pseudo code:
union u { short s; // or use int16_t more specific // vs. struct byte { char c1, c2; // or use int8_t more specific } byte; };
usage simple:
u u; u.s = 0x3210; std::cout << u.byte.c1 << " , " << u.byte.c2;
the concept simple, afterwards can overload operators make more fancy if want.
important note depending on compiler order of c1
, c2
may differ, known before compilation. can set conditinal macros make sure order according needs in compiler.
Comments
Post a Comment