int max = ~0; What does it mean?

前端 未结 8 2003
灰色年华
灰色年华 2021-01-19 03:46

int max = ~0;

What does it mean?

相关标签:
8条回答
  • 2021-01-19 04:29

    The ~ operator is the unary bitwise complement operator which computes the bitwise complement. This means that it reverses all the bits in its argument (0s become 1s and 1s become 0s). Thus,

    int max = ~0;
    

    which is setting max to the negation of the 32-bit value 0000 0000 0000 0000 0000 0000 0000 0000 resulting in 1111 1111 1111 1111 1111 1111 1111 1111. As we are storing this result in an Int32, this is the same as -1.

    Whether or not it is better to say

    int max = ~0;
    

    or

    int max = -1;
    

    depends on the context. If the point of max is to have a number all of whose bits are 1 I would choose the former. If the point of max is to compute the maximum of a list of non-negative integers, I would choose the latter (well, I'd prefer int max = Int32.MinValue; and even more so, I'd just prefer int max = list.Max();).

    0 讨论(0)
  • 2021-01-19 04:34

    As noted, ~0 yields 0xFFFFFFFF.

    However, I suspect the original programmer is confused. executing int max = ~0 ; sets the signed integer max to the value -1.

    0 讨论(0)
  • 2021-01-19 04:37

    ~ means bitwise not, it inverts all the bits in the given integer. In a signed int this will give you -1 (since all the bits in the int will be flipped from 0 to 1.) Look up two's complement for more information on this one.

    In an unsigned int (uint) this would give you the maximum value of an integer (since the most significant bit in an unsigned int doesn't determine the sign.)

    0 讨论(0)
  • 2021-01-19 04:39

    The ~ operator is a bit inverse, so ~0 gives you an integer value with all ones (in binary).

    0 讨论(0)
  • 2021-01-19 04:40

    ~ is the complement operator, which flips the bits of the operand. Since zero has no bits set, the complement will have all bits set, which is also the maximum sized integer (assuming unsigned). For signed numbers, you're going to get -1 instead, so calling it "max" is a bit of a misnomer.

    0 讨论(0)
  • 2021-01-19 04:41

    It is a bitwise negation of the bytes 0000....0000. It is the value of an integer where all bits are set to 1.

    In an unsigned situation it would be the maximum possible value. In a signed situation it is -1.

    0 讨论(0)
提交回复
热议问题