0

I tried to make 11..10..0 (which is binary number with consecutive 32-n zeros in small digits).

// Can assume that 0 <= n <= 31

int masking(int n) {
  return (~0)<<(~n+33);
}

However, when I put 0 in input n, I expected 0, but I got -1(0xffffffff).

Without using input,

  • (~0)<<(~0+33) gives 0.

  • (-1)<<32 also gives 0.

I don't know why I got different results.

Kalana
  • 5,631
  • 7
  • 30
  • 51
Guseul Heo
  • 28
  • 4

1 Answers1

1

You might want to consider forcing 64 bit math. According to "C" standard, result of shifting of a variable with N bits is only defined when the number of shifts is less than the size of the variable (0..N-1)

Performing the shift on (~0) (integer, usually 32 bit), will result in undefined behavior for ~n+33 (n=0) since ~n+33 = 32, above the limit of 31.

Changing the code to use (~0L) produce the requested result masking(0) = 0

Assuming that you run on generic Linux - gcc will default to 32 bit integer, 64 bit long and 64 bit pointer.

include <stdio.h>

int masking(int n) {
  return (~0UL)<<(~n+33);
}

void main(void)
{
        for (int i=0 ; i<4 ; i++) {
                printf("M(%d)=%x\n", i, masking(i)) ;
        }
}

Output:

M(0)=0
M(1)=80000000
M(2)=c0000000
M(3)=e0000000
dash-o
  • 13,723
  • 1
  • 10
  • 37
  • For additional technical discussion, look at: https://stackoverflow.com/questions/3784996/why-does-left-shift-operation-invoke-undefined-behaviour-when-the-left-side-oper – dash-o Sep 29 '19 at 12:01
  • `~0L` is still signed, so shifting it to the left is [still](https://stackoverflow.com/q/3784996/11683) undefined behaviour. – GSerg Sep 29 '19 at 19:48