[CrackCode] 5.1 Set all bits between i and j in N equal to M

本文介绍了一种通过位操作实现将一个32位数N中从i到j位置之间的比特位替换成另一个32位数M的方法。具体步骤包括:首先将N中i到j位置的比特位清零;其次将M左移i位;最后将处理后的N与左移后的M进行按位或运算得到最终结果。

You are given two 32-bit numbers, N and M, and two bit positions, i and j Write amethod to set all bits between i and j in N equal to M (e g , M becomes a substring ofN located at i and starting at j)


EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6Output: N = 10001010100 

===========

Analysis:

Step 1, set bits between i and j to 0 in n.

Step 2, m left shift i.

Step 3, n&m.

	public static int updateBits(int n, int m, int i, int j){
		int allOne = ~0; 
		int left = allOne<<j+1; // left to right, all 1 till position j+1, then all 0
		int right = (1<<i)-1; // right to left, all 1 till position i-1, then all 0
		int mask = left|right; // 0 from position i to position j, others all 1
		return (n&mask)|(m<<i); 
	}
	
	public static void main(String[] args) {
		int a = 103217;
		System.out.println(AssortedMethods.toFullBinaryString(a));
		int b = 13;
		System.out.println(AssortedMethods.toFullBinaryString(b));		
		int c = updateBits(a, b, 4, 7);
		System.out.println(AssortedMethods.toFullBinaryString(c));
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值