#include <stdio.h>

#define BIG_MASK(x,y) (1 << ((x > y) ? x:y))

#define SMALL_MASK(x,y) (1 << ((x > y) ? y:x))

#define BIT_DIFF(x,y) (x-y)

#define SWAP_BITS(num,x,y) ((num & ~(BIG_MASK(x,y) | SMALL_MASK(x,y))) | \

((num & BIG_MASK(x,y)) >> BIT_DIFF(x,y)) | \

((num & SMALL_MASK(x,y)) << BIT_DIFF(x,y)))

//Example:

//x = (x & ~0x14) | ((x & 0x10) >> 2) | ((x & 0x04) << 2);

int main()

{

printf("Hello, World!\n");

int a = 0x30;

int bitpos1 = 5;

int bitpos2 = 2;

printf("0x%x\n",a);

printf("0x%x\n",BIG_MASK(bitpos1,bitpos2));

printf("0x%x\n",SMALL_MASK(bitpos1,bitpos2));

printf("0x%x\n",SWAP_BITS(a,bitpos1,bitpos2));

return 0;

}

Output:

Hello,World!

0x30

0x20

0x4

0x14

#define BIG_MASK(x,y) (1 << ((x > y) ? x:y))

#define SMALL_MASK(x,y) (1 << ((x > y) ? y:x))

#define BIT_DIFF(x,y) (x-y)

#define SWAP_BITS(num,x,y) ((num & ~(BIG_MASK(x,y) | SMALL_MASK(x,y))) | \

((num & BIG_MASK(x,y)) >> BIT_DIFF(x,y)) | \

((num & SMALL_MASK(x,y)) << BIT_DIFF(x,y)))

//Example:

//x = (x & ~0x14) | ((x & 0x10) >> 2) | ((x & 0x04) << 2);

int main()

{

printf("Hello, World!\n");

int a = 0x30;

int bitpos1 = 5;

int bitpos2 = 2;

printf("0x%x\n",a);

printf("0x%x\n",BIG_MASK(bitpos1,bitpos2));

printf("0x%x\n",SMALL_MASK(bitpos1,bitpos2));

printf("0x%x\n",SWAP_BITS(a,bitpos1,bitpos2));

return 0;

}

Output:

Hello,World!

0x30

0x20

0x4

0x14

## 0 comments :

## Post a Comment