What does ~0 do?

前端 未结 4 1967
有刺的猬
有刺的猬 2020-12-11 08:13

Does ~0 mean its flipping 000000000 to 1111111111?

printf(\"Check: %i\", ~0);

The printf results to -1, which is why I am confused. <

相关标签:
4条回答
  • 2020-12-11 08:46

    Does ~0 mean its flipping 000000000 to 1111111111?

    Yes, it does.

    Does -1 essentially mean the same thing as 11111111111111111 bits?

    In 2s complement representation, it does.

    0 讨论(0)
  • 2020-12-11 08:56

    It is due to the mathematical operation "two's complement". A nice video tutorial of two's complement can be found on youtube. Here's one of them :)

    youtube link

    0 讨论(0)
  • 2020-12-11 09:00
    Does ~0 mean its flipping 000000000 to 1111111111?
    

    Yes, that's what it means.

    printf("Check: %i", ~0);
    
    The printf results to -1, which is why I am confused.
    

    That's because of 2's complement arithmetic, where we have conventionally accepted zero to be

    000000000000
    

    and subtracting one from it requires a "borrow" that requires a borrow, and so on, until you "roll" the entire register

    111111111111
    

    Logically, if you add "1" to that number, it will carry, and carry, and so on until it "rolls" in the opposite direction, yielding 000000000 again.

    Does -1 essentially mean the same thing as 11111111111111111 bits?
    

    Yes, as long as you are using 2's complement signed integers.

    ---- Edited, to include details from cincutar's now deleted post (I wish he didn't delete it) ---

    To see the same memory formatted as a (unsigned) hexadecimal number, use the command

    printf("Check: %x", ~0);
    

    which will print the output

    Check ffffffff
    

    which is (for those who don't read hexadecimal well)

    11111111111111111111111111111111
    
    0 讨论(0)
  • 2020-12-11 09:00

    ~0 == 0xFFFFFFFF

    where 0xFFFFFFFF= 32 times 1 , which is -1 in 2's compliement representation

    since ~ is a bitwise operation and turns zero to one in each bit:

    ~0b1010 == 0b0101
    
    0 讨论(0)
提交回复
热议问题