Tuesday, July 31, 2012

Reverse the bits in an integer

#include <stdio.h>

int revint(int num)
{
    int result=0;
    while(num)
    {
        result<<=1;
        result|=num%2;
        num>>=1;
    }
    return result;
}

char *basecalc(int num,int base)
{
    static char buff[32];
    char *s = &buff[31];
    *s='\0';
    while(num)
    {
        *(--s)="0123456789ABCDEF"[num%base];
        num/=base;
    }
    return s;
}

int main(void)
{
    int num;
    printf("\nEnter the num: ");
    scanf("%d",&num);
    printf("The num: %s\n",basecalc(num,2));
    printf("The rev int: %s\n",basecalc(revint(num),2));
    return 0;
}

No comments: