Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.63 shift 32 bits error #56

Open
swy20190 opened this issue Mar 25, 2020 · 2 comments
Open

2.63 shift 32 bits error #56

swy20190 opened this issue Mar 25, 2020 · 2 comments

Comments

@swy20190
Copy link

unsigned srl(unsigned x, int k) {
  unsigned xsra = (int) x >> k;

  int w = sizeof(int) << 3;
  //原来这句代码在k==0时会出左移32位的问题:int mask = (int) -1 << (w - k); ,改为以下这句
  int mask;
  ((k==0)&&(mask=(int)-1<<(w-k-1)<<1))||((k)&&(mask=(int)-1<<(w-k)));
  int mask = (int)-1<<(w-k
  return xsra & ~mask;
}
@userheng
Copy link

userheng commented May 7, 2020

unsigned srl(unsigned x, int k){
	//算术右移 
	unsigned xsra = (int)x >> k;
	int w =  sizeof(x) <<  3;
       //以2来作为移位的基数是比较简单的解决边界问题的一种方式,这样 k=0 代码也可以正常工作
	int mask = (2 << (w - k - 1)) + (-1);
	return mask & xsra;
} 

int sra(int x, int k){
	//逻辑右移 
	int xsrl = (unsigned)x >> k; 	
	int w =  sizeof(x) <<  3;
	int mask = -2 << (w - k - 1);
	return mask | xsrl;
}

@geethubccc
Copy link

sixsixsix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants