左移右移為負數的情況


C語言中,移位操作是經常用到的
到時有個現象是i<<-1i<<31的結果一樣
1 “-1”表示成補碼是1111 ….11 1111 ,31是 0000 …0011 1111,,他們的后六位是一樣的。
Interger的移位運算只注意后6位

Note also that rotation by any multiple of 32 is a no-op, so all but the last five bits of the rotation distance can be ignored, even if the distance is negative:

總結:將負數寫為補碼,這個數的低6位便是其真正移位的數字

int main()
{
	int size = 1;
	int sz1 = size << 1;
	int sz2 = size << 193;

	if (sz1 == sz2)
	{
		printf("sz1==sz2\n");
	}
	else
	{
		printf("sz1==sz2\n");
	}
	return 0;
}

結果 sz1==sz2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM