## NVIDIA Interview Question

int insert (int N, int a, int b, int k) {

/* Determine what are needed to be inserted */

int pattern = k & (2<<(b-a))-1; /* Mask the required bits from k */

/* Clear the dst bits and OR with the src pattern */

N = N & ~(2<<(b-a)-1) | pattern;

return N;

}

Hey,

with this example both above algos fail.

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.

int insert(int x, int a, int b, int k)

- jvt August 09, 2007{

int y = a;

k= k<<a;

y = y >> (b + 1);

y= y << (b + 1);

y = y|k;

x = y|x;

return(x);

}