bitwise not operator

前端 未结 10 985
广开言路
广开言路 2021-01-30 16:24

Why bitwise operation (~0); prints -1 ? In binary , not 0 should be 1 . why ?

相关标签:
10条回答
  • 2021-01-30 16:55

    It's binary inversion, and in second complement -1 is binary inversion of 0.

    0 讨论(0)
  • 2021-01-30 16:56

    What you are actually saying is ~0x00000000 and that results in 0xFFFFFFFF. For a (signed) int in java, that means -1.

    0 讨论(0)
  • 2021-01-30 17:00

    Because ~ is not binary inversion, it’s bitwise inversion. Binary inversion would be ! and can (in Java) only be applied to boolean values.

    0 讨论(0)
  • 2021-01-30 17:01

    I think the real reason is that ~ is Two’s Complement.

    Javascript designates the character tilde, ~, for the two’s complement, even though in most programming languages tilde represents a bit toggle for the one’s complement.

    0 讨论(0)
  • 2021-01-30 17:03

    In standard binary encoding, 0 is all 0s, ~ is bitwise NOT. All 1s is (most often) -1 for signed integer types. So for a signed byte type:

    0xFF = -1    // 1111 1111
    0xFE = -2    // 1111 1110
    ...
    0xF0 = -128  // 1000 0000
    0x7F = 127   // 0111 1111
    0x7E = 126   // 0111 1110
    ...
    0x01 = 1     // 0000 0001
    0x00 = 0     // 0000 0000
    
    0 讨论(0)
  • 2021-01-30 17:03

    For 32 bit signed integer

    ~00000000000000000000000000000000=11111111111111111111111111111111 (which is -1)

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