Interview Questions

two 32bit integers m,n are given.replace all the bits......

Microsoft Interview Questions and Answers


(Continued from previous question...)

35. two 32bit integers m,n are given.replace all the bits......

Question:
two 32bit integers m,n are given.replace all the bits in m from i to j locations with all the bits in n from k to l locations....
eg.m=110000000000 n=10101010 i=3 j=5 k=5 l=7
o/p:110000101000

some one give me the solution


maybe an answer:

//Simply, I would like to separately get (cut of) the bits from position k to
//position L from number n
//This can be done be shifting number n to the left (31-L) times
//Then Shift to the right ((31-L) + k )times. This will make the number n only
//contains the bits from position k to position L.
//These bits will be at the beginning (right side) of the
//number n. Shifting n to the left i times will position the bits of n in the
//required position of m. Finally do OR operation between m and n.

void Main()
{
uint m = 0x00000C00;
uint n = 0x000000AA;
Console.Write("i: "); int i = int.Parse(Console.ReadLine());
Console.Write("j: ");
int j = int.Parse(Console.ReadLine());
Console.Write("k: ");
int k = int.Parse(Console.ReadLine());
Console.Write("l: ");
int L = int.Parse(Console.ReadLine());
n <<= (31 - L);
n<<= ((31-L)+k);
n <<= i;
m |= n;
Console.WriteLine("{0:X



maybe an answer2:
It can be solved with bitmask .. Firstly we take a copy of bits in n & m and replace them .. here is a simple code

void solve ( int &a , int &b ,int i , int j , int k , int l )
{
vector<int> aa, bb ;
for ( int co=i ; co<=j ; co++ )
aa.push_back( a&(1<<co) ) ;
for ( int co=k ; co<=l ; co++ )
bb.push_back( b&(1&<<co) ) ;
for ( int ii=0 ; ii<aa.size() ; ii++ )
{
if ( aa[ii] )
b |= (1<<ii+k) ;
else
b &= ~(1<<(ii+k));
}
for ( int ii=0 ; ii<bb.size() ; ii++ )
{
if ( bb[ii] )
a |= (1<<ii+i) ;
else
a &= ~(1<<(ii+i));
}
return ;

(Continued on next question...)

Other Interview Questions