What is the purpose of “int mask = ~0;”?

前端 未结 6 650
春和景丽
春和景丽 2020-12-29 18:30

I saw the following line of code here in C.

 int mask = ~0;

I have printed the value of mask in C and C++. It always prints

6条回答
  •  旧时难觅i
    2020-12-29 19:04

    You are studying a coding challenge with a number of restrictions on operators and language constructions to perform given tasks.

    The first problem is return the value -1 without the use of the - operator.

    On machines that represent negative numbers with two's complement, the value -1 is represented with all bits set to 1, so ~0 evaluates to -1:

    /* 
     * minusOne - return a value of -1 
     *   Legal ops: ! ~ & ^ | + << >>
     *   Max ops: 2
     *   Rating: 1
     */
    int minusOne(void) {
      // ~0 = 111...111 = -1
      return ~0;
    }
    

    Other problems in the file are not always implemented correctly. The second problem, returning a boolean value representing the fact the an int value would fit in a 16 bit signed short has a flaw:

    /* 
     * fitsShort - return 1 if x can be represented as a 
     *   16-bit, two's complement integer.
     *   Examples: fitsShort(33000) = 0, fitsShort(-32768) = 1
     *   Legal ops: ! ~ & ^ | + << >>
     *   Max ops: 8
     *   Rating: 1
     */
    int fitsShort(int x) {
      /* 
       * after left shift 16 and right shift 16, the left 16 of x is 00000..00 or 111...1111
       * so after shift, if x remains the same, then it means that x can be represent as 16-bit
      */
      return !(((x << 16) >> 16) ^ x); 
    }
    

    Left shifting a negative value or a number whose shifted value is beyond the range of int has undefined behavior, right shifting a negative value is implementation defined, so the above solution is incorrect (although it is probably the expected solution).

提交回复
热议问题