Friday, 21 November 2014

Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted. You can assume that x,p & n are integer variables and that the function will return an integer.

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
            int intUserInput, intUserInput1, intUserInput2;
            int intCompResult;
            int invert(int, int, int);
            clrscr();
            printf("\n\n\t Please insert integer to invert: ");
            scanf("%d", &intUserInput);

            printf("\n\n\t Please insert starting point to invert: ");
            scanf("%d", &intUserInput);

            printf("\n\n\t Please insert Length to invert: ");
            scanf("%d", &intUserInput2);

            intCompResult=invert(intUserInput, intUserInput1, intUserInput2);
            printf("\n\n\t Invert no. is : %d", intCompResult);
            getch();
}
int invert(int x, int p, int n)
{
            int intbinary[8];
            int i;
            int y;
            int r=0;
            for(i=0;i<8;i++)
            {
                        intbinary[i]=0;
            }
            i=0;
            y=0;
            while(x>0)
            {
                        intbinary[i]=x%2;
                        x=x/2;
                        i++;
            }
            for(i=0;i<8;i++)
            {
                        if(i==p)
                        {
                                    for(i=p;i>p-n;i--)
                                    {
                                                if(intbinary[i]==0)
                                                {
                                                            intbinary[i]=1;
                                                }
                                                else
                                                {
                                                intbinary[i]=0;
                                                }
                                    }
                                    i=i+n;
                        }
            }
            for(i=0;i<8;i++)
            {
                        r=r+(intbinary[i]*pow(2,i));
            }
            return r;

}

No comments:

Post a Comment

Please write your doubts