Swap byte 2 and 4 from integer

Posted by czar x on Stack Overflow See other posts from Stack Overflow or by czar x
Published on 2013-07-01T17:04:31Z Indexed on 2013/07/01 17:05 UTC
Read the original article Hit count: 167

Filed under:

I had this interview question - Swap byte 2 and byte4 within an integer sequence. Integer is a 4byte wide i.e. 32 bits

My approach was to use char *pointer and a temp char to swap the bytes.

For clarity i have broken the steps otherwise an character array can be considered.

unsigned char *b2, *b4, tmpc;
int n = 0xABCD;
b2 = &n;   b2++;  
b4 = &n;   b4 +=3;
///swap the values;
tmpc = *b2;
*b2 = *b4;
*b4 = tmpc;

Any other methods?

© Stack Overflow or respective owner

Related posts about c