Swap Two Bits in a Number of Any Type - Swap Bit position in C with Example Code

#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

Related Post:


Removing Space from Given String & Different Methods to Count Number of Ones in Given Value

Booting Sequence for Boot Process in Linux

How to count number of 1 or set bits in a given number

What is Segmentation fault ?

How to Access Private Data Members in C++ without using friend function

Process Vs Thread 

How to Add Two Numbers Without Using + Operator in C 

Overview of Function Pointer in C with Example - What is function pointer & how to use it

How to Fork child process with waitpid & execl in linux with c example code

Share on Google Plus

About Kapil Thakar

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...