位操作插入


class UpdateBits 
{
// Function to updateBits M insert to N.
static int updateBits(int n, int m, int i, int j)
{
/* Create a mask to clear bits i through j
in n. EXAMPLE: i = 2, j = 4. Result
should be 11100011. For simplicity, we'll
use just 8 bits for the example. */

int allOnes = ~0; // will equal sequence of all ls

// ls before position j, then 0s. left = 11100000
int left= allOnes << (j + 1);

// l's after position i. right = 00000011
int right = ((1 << i) - 1);

// All ls, except for 0s between i and j. mask 11100011
int mask = left | right;

/* Clear bits j through i then put min there */
// Clear bits j through i.
int n_cleared = n & mask; 
// Move m into correct position.
int m_shifted = m << i;  

// OR them, and we're done!
return (n_cleared | m_shifted); 
}

public static void main (String[] args) 
{
// in Binary N= 10000000000
int n = 1024; 

// in Binary M= 10011
int m = 19;   

int i = 2, j = 6;

System.out.println(updateBits(n,m,i,j));
}
}

我无法理解这句话:

int right = ((1 << i) - 1);

1 << i表示将1 i位向左移位。如果i是2,这将导致比特为00000100。不管i是多少,我们总是有一个1,后面跟着i 0。

现在取负1,得到00000011。如果你熟悉二进制,你应该看到,取一个正好有一个1减去1的二进制数,总是会得到一个先有零后有一的二进制数(regex:0*1*(。

所以总的来说,你得到了一个数字,它的末尾正好有i个比特作为1。

最新更新