I am missing a couple of parentheses. So make that

N = (N & ~((2 << j) - (1 << i))) | (M << i);

And to make up for the extra post to get it right, I'll explain it:
2<<j is a one bit in bit position j+1 and 0 bits elsewhere.
1<<i is a one bit in bit position i and 0 bits elsewhere.
The difference of the two is a number with one bits from positions i
to and including j, and 0 bits elsewhere.
~that is a number with 0 bits from positions i to and including j and
1 bits elsewhere.
N&that is the number N with the bits from positions i to and including
j set to zero.
M<<i is M shifted into the correct position.
| puts the two pieces together.

In the above, I've assumed that the field consisting of bits i through
j inclusive are to be modified. If what is intended is that i is the
first bit modified and j is the first bit not modified (so that j-i
bits are modified), then change 2<<j to 1<<j.

Dave

Dave

On Sep 20, 11:41 am, Dave <[email protected]> wrote:
> @Ishan: Using bitwise operations:
>
> N = (N & ~((2 << j) - (1 << i) | (M << i);
>
> Dave
>
> On Sep 20, 2:03 am, Ishan Aggarwal <[email protected]>
> wrote:
>
>
>
> > You are given two 32-bit numbers, N and M, and two bit positions, i and
> > j.Write a method to set all bits between i and j in N equal to M (e.g., M
> > becomes a substring of N located at i and starting at j).
>
> > EXAMPLE:
>
> > Input: N = 10000000000, M = 10101, i = 2, j = 6
>
> > Output: N = 10001010100
>
> > --
> > Kind Regards
> > Ishan Aggarwal
> > [image: Aricent Group]
> > Presidency Tower-A, M.G.Road,Sector-14
> > Gurgaon,Haryana.122015 INDIA
> > Phone : +91-9654602663
> > [email protected] <[email protected]>- Hide quoted text -
>
> - Show quoted text -

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to