user3053970 user3053970 - 2 months ago 8
C Question

Swap alternate bytes in a integer

Problem: swap alternate bytes as below:

Input: uint8_t buf[4] = {0xab,0xcd,0xef,0xba};

Output: 0xcdababef

I have the below code for doing that but I am wondering if there is any better way to shorten the code.

#include <stdint.h>
#define SWAP_16(buf) (((buf & 0xFF00) >> 8) | ((buf & 0x00FF) << 8))
int main()
{
unsigned int value;
int i, j=0;
uint8_t buf[4] = {0,4,0,0};
unsigned int mask = 0xFFFF;
unsigned int tmp_value;
unsigned int size = 4;

for (i = size - 1 ;i >= 0; i--) {
tmp_value |= (buf[j] << 8*i);
j++;
}

value = SWAP_16((tmp_value & (mask << 16)) >> 16) << 16 |
SWAP_16(tmp_value & mask);
return 0;
}

Answer

Assuming unsigned int is 32-bits, you can simply use:

value = ((value & 0xff00ff00) >> 8) | ((value & 0x00ff00ff) << 8);

to swap the bytes in each pair of bytes in value. It's similar to your SWAP_16() macro except that it does both halves of the value at once.