简体   繁体   中英

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.

For example, if getMask(2,6,1) is called the result is: 00000000000000000000000001111100

For some reason when I call getMask(0,31,1) I get: 00000000000000000000000000000000 instead of 11111111111111111111111111111111

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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