0

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?

1
  • 3
    You're using int, which is likely 32 bits on your system. Unsigned shifting is performed modulo number of bits, but signed shifts (what you're doing) are undefined behavior if you shift >= the number of total bits. Reference Commented Apr 7, 2019 at 19:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Would this work if it returned a regular int and not unsigned. That is a requirement for my assignment.
yes it would. I invite you to test it and play a bit with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.