Swapping 2 Bytes of Integer

Couple of things

You can recombine by masking x with a value that is all FF except for bytes m and n You can compute the mask by left shifting 0xFF m times and n times and combining the result and then XOR it with 0xFFFFFFFF

int mask = 0;
int mask_m = 0xFF << (m << 3);
int mask_n = 0xFF << (n << 3);

mask = (mask_m | mask_n) ^ 0xFFFFFFFF;

int x_swapped = (x & mask) | (xm << (n <<3)) | (xn << (m <<3));
return x_swapped;

FYI when you right shift a signed value, it may or may not propagates 1s instead of 0 into the high order bit and is implementation defined. Either way 0xFF will protect against that.

cbyteswapbyte-shifting

Leave a Comment