把一个数插入另一个数

given two 32bit 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 t hrough i have enough space to fit all of M/

input N = 100 0000 0000 M = 10011, i = 2, j = 6

output N = 100 0100 1100

int setMask(int i, int j){
	int len = j-i+1;
	int result = 1;
	while(len>1){
		result = (result<<1)+1;
		len--;
	}
	while(i>0){
		result = result << 1;
		i--;
	}
	return result;
}
int setBit(int n, int m, int i, int j){
	if (i>j){
		cout<<"Error: i>j" <<endl;
		return 0;
	}
	if (i<0 || j>31){
		cout<<"Error: i,j range is wrong" <<endl;
		return 0;
	}

	int tempm = m;
	int lenm = 0;
	while(tempm){
		tempm= tempm >> 1;
		lenm++;
	}
	if (j-i+1>lenm)
		j = i+lenm-1;
	int mask = setMask(i,j);
	n &= ~mask;
	while(i>0){
		m = m<<1;
		i--;
	}
	n |= m;
}

1. 注意边界检查

2. 这个set mask的方法太复杂了,自己都看不下去了……

int allones = ~0;
int left = allones<<(j+1);
int right = (1<<i)-1;
int mask = left|right;

3. 原来写的 m<<1,  这样是错的,这样并不能改变m的值,应该改为m <<=1





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值