5.1

来源:互联网 发布:知乎年度吐槽精选 编辑:程序博客网 时间:2024/06/05 00:38

Topic 5.1 You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all M. That is, if M=10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j=3 and i=2, because M could not fully fit between bit 3 and bit 2.

EXAMPLE: input: N=10000000000, M=10011, i=2, j=6; Output: N=10001001100

Three steps:

1. Clear the bits j through i in N -----do this with a mask

2. Shift M so that it lines up with bits j through i

3. Merge M and N

import java.math.BigInteger;public class c5_1 {public static int updateBits(int n, int m, int i, int j) {if (i >= 32 || j < i) {return 0;}/* Create a mask to clear bits i through j in n/* EXAMPLE: i = 2, j = 4. Result should be 11100011. * (Using 8 bits for this example.  This is obviously not actually 8 bits.) 要让第i到j位为0,其他位为1*/int allOnes = ~0; // allOnes = 11111111//这三句有意思int left = allOnes << (j + 1); // 1s through position j, then 0s. left = 11100000  int right = ((1 << i) - 1); // 1’s after position i.  right = 00000011int mask = left | right; /* Clear i through j, then put m in there */int n_cleared = n & mask; // Clear bits j through i.int m_shifted = m << i; // Move m into correct position.return n_cleared | m_shifted; }public static void main(String[] args) {String n ="10000000000";BigInteger src=new BigInteger(n,2);System.out.println("n="+src.toString());String m="10011";BigInteger src2=new BigInteger(m,2);System.out.println("m="+src2.toString());int c=updateBits(1024,19,2,6);System.out.println("After updating: "+Integer.toBinaryString(c));}}
//结果n=1024m=19After updating: 10001001100



 

原创粉丝点击