Swap Adjacent Even & Odd Bits of Any Type of Variable in C

#include "stdafx.h"
#include <conio.h>

#include <stdio.h>


int bitMask1[8]= {0xaa,0xaaaa,0xaaaaaa,0xaaaaaaaa,0xaaaaaaaaaa,0xaaaaaaaaaaaa,0xaaaaaaaaaaaaaa,0xaaaaaaaaaaaaaaaa};

int bitMask2[8]= {0x55,0x5555,0x555555,0x55555555,0x5555555555,0x555555555555,0x55555555555555,0x5555555555555555};


int swapAdjBits(int x)

{
    return (((x & (bitMask1[sizeof(x)-1])) >> 1) | ((x & (bitMask2[sizeof(x)-1])) << 1));
}

#define SWAP_ADJ_BITS(x) (((x & (bitMask1[sizeof(x)-1])) >> 1) | ((x & (bitMask2[sizeof(x)-1])) << 1))



int _tmain(int argc, _TCHAR* argv[])

{
    printf("Hello, World!\n");
    char x = 23;
    int y = 23;

    long z = 23;

    printf("%d\n",swapAdjBits(x));
    printf("%d\n",SWAP_ADJ_BITS(x));
    printf("%d\n",swapAdjBits(y));
    printf("%d\n",SWAP_ADJ_BITS(y));
    printf("%d\n",swapAdjBits(z));
    printf("%d\n",SWAP_ADJ_BITS(z));
    getch();

    return 0;

}
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...