开发者

bit manipulation: modify the 32 bit integer to include the substring

two 32 bit numbers are given M and N . two bit positions are given i and j.The method should set all the bits between i and j in N equal to M .

N=10000000 M=1111 i=3 and j=7 output:N=10111100

    int modifybits(int i,int j,int N,int M)
    {

    int max=1;
    //the string from the left of i and right of j should remain the same and the rest should become 0
     int left= N>>31-i
     left=left<<31

    int right =N<<j
    right=right>>31-j

    int new_N=left|right
    int result=new_N|开发者_如何学GoM
    print(result)

    }

Can you provide a better solution ,this doesnt seem to work!!Thnx in adv


 int modifybits(int i, int j, int N, int M) {
      int mask = ~0; // mask with only 1
      int res = 0;

      // Note: We need the -1 here because you started numbering bits at 
      // the last position with 1 not with 0 as usual
      mask = mask >> (i - 1);
      mask = mask << (i - 1 + 32 - j - 1);
      mask = mask >> (32 - j - 1); // now mask should contain only 1 at the positions
                                 // we want to change in N 

      M = M & mask; // M is now only set at the masked bits
      N = N & (~mask); //we set all within mask to zero
      N = N | M;

      return N;
 }

Another note: I assumed here that 32bits is the size of ints on your system! Otherwise you should replace the 32 in the computation of the mask


Your question is not 100% clear. "The method should set all the bits between i and j in N equal to M" - but M usually has more bits than (j-i), do you want to use the same positions or positions 0..(j-i)? Also, in your example, you use index 1 for the lsb (right-most bit)?

You can do this using a bitfield. In your example, you want to replace bit 2-6 (?), so use the bitfield B = 01111100.

If you want to set N[2-6] to M[2-6], use N = (N & ~B) | (M & B).

If you want to set N[2-6] to M[0-4], use N = (N & ~B) | ((M << 2) & B).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜