set all bits between i and j in N equal to M

題目:

You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100

 

實現:

unsigned int SetBits(unsigned int N, unsigned int M, unsigned int i, unsigned int j)
{
	return (((N >> j) << j) | (M << i) | (N % (2 << i)));
}

說明:其中(N >> j) << j用於獲取N中j左邊的數據;M << i將M偏移i的位移,以便放到N中從i開始的位置;N % (2 << i)用於獲取N中i右邊的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章