Q43 Write a C program to reverse odd bits or even bits of an integer.

For reversing each odd bits of a given number, simply do XOR  ’^’ each of its 4 hex parts with 0101. See an example:

If we convert binary 0101 in hexadecimal then it will become 0x5

temp = number ^ 0x55555555  /* This statement reverse all odd bits of number */

 For reversing each even bits of a given number, simply do XOR  ’^’ each of its 4 hex parts with 1010. See an example:

If we convert binary 1010 in hexadecimal then it will become 0xA

temp = num ^ 0xAAAAAAAA /* This statement reverse all even bits of number */

2 comments

  1. /* reverse even bits only without affecting even bits */
    #include
    int reverse(int);
    void displaybits(int);
    int main()
    {
    int a;
    printf(“enter Number\n”);
    scanf(“%i”,&a);
    displaybits(a);
    // printf(“%x”,reverse(a));
    displaybits(reverse(a));
    }

    int reverse(int a)
    {
    unsigned int reverse_num=0,i,temp;
    unsigned int odd_bits=a&0x55555555;
    unsigned int even_bits=a&0xAAAAAAAA;
    for(i=1;i<32;i=i+2)
    {
    temp=(a & (1<<i));
    // printf("temp:%d",temp);
    if(temp)
    reverse_num |= (1<0)
    {
    if(x & MASK)
    printf(“1”);
    else
    printf(“0″);
    printf(” “);
    MASK=MASK>>1;
    }
    printf(“\n”);

    }

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.