Interview Question

Anonymous Interview Santa Clara, CA

Write a c functions that takes two bit indices and an int

  , and reverses the bits in the int between the two indices.
Answer

Interview Answer

4 Answers

This post has been removed.
Please see our Community Guidelines or Terms of Service for more information.

0

//reverses bit between two indices of a number.
#include<iostream>
using namespace std;
int main()
{
unsigned int no=90,i=2,j=6,tmp=0,tmp1=0;
tmp=no>>i;
cout<<tmp<<" tmp\n";
for(unsigned int x=0;x<=j-i;x++)
{
tmp1=tmp1<<1;
tmp1=tmp1|(tmp&1);
tmp=tmp>>1;
}
cout<<tmp1<<"tmp1 \n";
tmp=0;
for(unsigned int x=0;x<=(int)(sizeof(int)*8-1);x++)
{
tmp=tmp>>1;
if(x<=j && x>=i)
tmp=tmp|0;
else
tmp=tmp|0x80000000;
}
cout<<tmp<<"tmp before\n";
no=no&tmp;
no=no|(tmp1<<i);
cout<<no<<" no";
return 0;
}

noty on Apr 1, 2011
0

#include <stdio.h>
main(int arg, char *argv[])
{
    unsigned char num, hi_indx, lo_indx, mask, num_tmp, mask_c, num_rv, iter,i;
    num = atoi(argv[1]);
    hi_indx = atoi(argv[2]);
    lo_indx = atoi(argv[3]);

    mask = ((0xFF << (7-hi_indx))) ;
    mask = mask >> (7-hi_indx+lo_indx);
    mask = (mask << lo_indx);
    mask_c = ~mask;
    num_tmp = num & mask_c;
    printf("%x %d %d %x",num, hi_indx, lo_indx, mask);

    num_rv = 0x0;

    iter = hi_indx-lo_indx+1;
    i = 0;
    while(i<=iter)
    {
        int flg;
        flg=(num & (1<<(i+lo_indx)))?1:0;
        if(flg)
            num_rv=num_rv|(1<<(hi_indx-i));
        i++;
    }

    num = num_rv | num_tmp;
    printf("\nnum=%x ",num);

}

Anonymous on Nov 3, 2012
0

The above one is just to give an example with 8bits

Anonymous on Nov 4, 2012

Add Answers or Comments

To comment on this question, Sign In with Facebook or Sign Up