在小节[i,j]的周围为数字创建遮罩 [英] Creating a mask around a subsection [i,j] for a number

查看:78
本文介绍了在小节[i,j]的周围为数字创建遮罩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习位操作和按位运算符,并且正在研究一个实践问题,您必须将int M的小节[i,j]合并到[i,j]处的N中.我以线性方式创建了蒙版,但是在谷歌搜索后发现〜0<< j | ((1<< i)-1)创建我想要的蒙版.但是,我不确定为什么.如果有人可以提供说明,那就太好了,谢谢.

I'm learning bit manipulation and bitwise operators currently and was working on a practice problem where you have to merge a subsection[i,j] of an int M into N at [i,j]. I created the mask in a linear fashion but after googling i found that ~0 << j | ((1 << i) - 1) creates the mask I wanted. However, I am not sure why. If anyone could provide clarification that would great, thanks.

void merge(int N, int M, int i, int j){
    int mask = ~0 << j | ((1 << i) - 1);
    N = N & mask; // clearing the bits [i,j] in N
    mask = ~(mask); // inverting the mask so that we can isolate [i,j] in 
//M
    M = M & mask; // clearing the bits in M outside of [i,j]
    // merging the subsection [i,j] in M into N at [i,j] by using OR
    N = N | M; 
}

推荐答案

~0是所有1位"的数字.当将其上移j时,会将最低有效的j位放入0:

~0 is the "all 1 bits" number. When you shift it up by j, you make the least significant j bits into 0:

1111111111111111  ==  ~0  ==  ~0 << 0
1111111111111110  ==  ~0 << 1
1111111111100000  ==  ~0 << 5
1111111110000000  ==  ~0 << 7

1 << i只是打开的i + 1最低有效位.

1 << i is just the i + 1th least significant bit turned on.

0000000000000001  ==  1 << 0
0000000000000010  ==  1 << 1
0000000000001000  ==  1 << 3
0000000001000000  ==  1 << 6

当您从中减去1时,有一个从左一直到位,因此在1位变为1之前,您将剩下所有位(因此,您得到的前i个最低有效位最终打开).

When you subtract 1 from this, there is a one carried all the way from the left, so you are left with all the bits before the 1 bit becoming 1 (So you end up with the first i least significant bits turned on).

0000000000000000  ==  (1 << 0) - 1
0000000000000001  ==  (1 << 1) - 1
0000000000000111  ==  (1 << 3) - 1
0000000000111111  ==  (1 << 6) - 1

当您或他们在一起时,最终会打开一个窗口,该窗口位于j最低有效位和i + 1最低有效位(包括)之间.

When you or them, you end up with a window between the jth least significant bit and the i + 1th least significant bit turned on (inclusive).

1111111110000000  ==  ~0 << 7
0000000000000111  ==  (1 << 3) - 1
1111111110000111  ==  ~0 << 7 | ((1 << 3) - 1)
         7   3  

使用此掩码&的数字时,将清除范围(i,j]中的位(不包括第i位本身).

When you & a number with this mask, you clear the bits in the range (i, j] (The ith bit itself is not included).

~掩码时,您会得到一个新的掩码,该掩码只会为您提供(i,j]范围内的位.

When you ~ the mask, you get a new mask that will only give you the bits in the range (i, j].

1111111110000111  ==  ~0 << 7 | ((1 << 3) - 1)
0000000001111000  ==  ~(~0 << 7 | ((1 << 3) - 1))

也可以用((1 << j) - 1) & ~((1 << i) - 1)之类的东西来构造.

Which could also be constructed with something like ((1 << j) - 1) & ~((1 << i) - 1).

这篇关于在小节[i,j]的周围为数字创建遮罩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆