~ operator in C

后端 未结 5 1442
星月不相逢
星月不相逢 2021-01-28 00:33

The output of this program is -13. I have never fully understood ~ operator in C. Why does it give -13 as output? How to limit ~ operator to just 4 bits of a number?

<         


        
5条回答
  •  伪装坚强ぢ
    2021-01-28 01:32

    To limit the effect to a specified number of bits, just use bitwise masks, e.g.:

    #include 
    
    int main(void) {
        int a = 16;             /* 10000 in binary */
        int b = ~a;             /* Will interpret b as -17 in two's complement */
        int c = (a & ~0xF) | (~a & 0xF); /* Will limit operator to rightmost 4 bits,
                                            so 00000 becomes 01111, and c will become
                                            11111, not 11...101111, so c will be 31     */
    
        printf("a is %d, b is %d, c is %d\n", a, b, c);
        return 0;
    }
    

    Outputs:

    paul@local:~/src/c/scratch$ ./comp
    a is 16, b is -17, c is 31
    paul@local:~/src/c/scratch$
    

提交回复
热议问题