NVIDIA Interview Question
int modifyInt(int n, int a ,int b, int k )
{
int temp1,temp2;
temp1=n;
n=n>>(b+1); /*right shift the number by b+1 bits
n=n <<(b+1);
/* left shift the above result by b+1 bits - this makes the last b+1 bits of n zero */
k=k >> a;
/*now right shift k by 'a' bits */
temp2=temp1 << (8*sizeof(int)-a);
temp2=temp2 >>(8*sizeof(int)-a);
/*temp2 now holds the value of the last 'a' bits of n */
temp1=temp1 | k;
/*this replaces the b+1 bits of n with k - now we need to shift this by a bits and concatenate with a to retain the original 'a' bits */
temp1= temp1 << a;
temp2=temp2 | temp1;
return(temp2);
}
int modifyInt(int n, int a ,int b, int k )
{
int temp1,temp2;
temp1=Oxffffffff;
temp1=temp1>>(a); /*right shift the number by a bits
temp1=temp1<<(a);
/* left shift the above result by a bits - this makes the last
a bits of n zero */
temp1=temp1<<(8*sizeof(int)-b);
temp1=temp1>>(8*sizeof(int)-b);
temp1=NOT(temp1);//invert the 1's and 0's
n=n&&temp1;
/*now right shift k by 'a' bits */
temp2=k << (a);
n=n||temp2;
return(n);
}
Hey,
if N=1011 K=0100 A=1 B=2
So we need to move bits 1 & 2 from K to N. So N becomes 1101
I did something like this
pattern = ~(~0<<(B-A+1))<<A;
N= (N& ~pattern)|( K & pattern);
First statement gives mask from location B to A.
Second just copies required bits from K to N.
For Ex. A=2 ,B=3
~0<<(B-A+1) = 11111100
~(~0<<(B-A+1)) = 00000011
Pattern = ~(~0<<(B-A+1))<<A = 00001100
1.And pattern with K then we get bits needs to be copied .
2. Use the same pattern to remove same bits from N (N &~ pattern).
or above two statements to get result.
#include <stdio.h>
int main() {
unsigned num = 8;
unsigned int a = 4;
unsigned int b = 7;
unsigned int k = 5;
unsigned int mask;
int r =0;
mask = ((unsigned int)~0<<a) & ((unsigned int)~0>>(31-b));
k = ((unsigned int)k<<a);
printf("%d\n",k);
// printf("%d %d\n",k,mask);
r = (num & ~mask) | k;
printf("%x",r);
int modifyInt(int n,int a, int b, int k)
- Anonymous November 28, 2007{
}