简体   繁体   English

移位并创建掩码

[英]Bit shifting and creating a mask

I am creating a method that takes 3 integers (start, end, z), the result should be a mask of either 1 or 0 depending on z from start to end. 我正在创建一个采用3个整数(开始,结束,z)的方法,结果应该是1或0的掩码,具体取决于z从开始到结束。

For example, if getMask(2,6,1) is called the result is: 00000000000000000000000001111100 例如,如果调用getMask(2,6,1),则结果为:00000000000000000000000001111100

For some reason when I call getMask(0,31,1) I get: 00000000000000000000000000000000 instead of 11111111111111111111111111111111 由于某些原因,当我调用getMask(0,31,1)时,我得到:00000000000000000000000000000000而不是11111111111111111111111111111111111

My method code is: 我的方法代码是:

if (z == 1)
{
   return ~(~0 << (end - start + 1)) << (start);
}
else if (z == 0)
{
    return ~(~(~0 << (end - start + 1)) << (start)); 
}

I want to know why I would be getting that result instead of the expected one. 我想知道为什么我会得到那个结果而不是预期的结果。

Edit: So i understand why it is happening but how do I fix it? 编辑:所以我明白为什么会这样,但是我该如何解决呢?

Here is a working version to it: 这是它的工作版本:

#include "limits.h"
#include <stdio.h>

unsigned int get_mask(int start, int end, int z);
void p(unsigned int n);
int main() {
    p(get_mask(2, 6, 1));
    p(get_mask(0, 31, 1));
    p(get_mask(0, 31, 0));
    p(get_mask(1, 31, 1));
    p(get_mask(1, 31, 0));
    p(get_mask(6, 34, 1));
}

unsigned int get_mask(int start, int end, int z) {
    int rightMostBit = end - start + 1;
    unsigned int res = ~0;
    if (rightMostBit < sizeof(int) * CHAR_BIT) {
        res = ~(res << rightMostBit);
    }
    res = res << start;
    if (z == 0) {
        res = ~res;
    }
    return res;
}

void p(unsigned int n) {
    for (int i = 31; i >= 0; --i) {
        if (n & (1 << i)) {
            printf("1");
        }
        else {
            printf("0");
        }
    }
    printf("\n");
}

I basically do the first shift and ~ only if it does not overflow. 我基本上会进行第一个班次,并且仅在不溢出的情况下进行〜。 If it does, the initial ~0 is already ready to be shifted of start bits. 如果是这样,则初始~0已经准备好start移位start位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM