The output value differs from the value received as argument within the function when performing a direct operation

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.

c
asked on Stack Overflow Sep 29, 2019 by Guseul Heo • edited Sep 29, 2019 by Kalana

1 Answer

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
answered on Stack Overflow Sep 29, 2019 by dash-o • edited Sep 30, 2019 by dash-o

User contributions licensed under CC BY-SA 3.0