How does C++ do bitwise “or” operations on negative numbers?

前端 未结 6 1767
野的像风
野的像风 2021-01-12 16:18

When I give to a variable such value: e = 17|-15; , I get -15 as an answer after compiling.I can\'t understand what arithmetic c++ uses. How does it perform a

6条回答
  •  时光说笑
    2021-01-12 17:08

    A bitwise or with a negative number works JUST like a bitwise or with a positive number. The bits in one number are ored with the bits in the other number. How your processor represents negative numbers is a different matter. Most use something called "two's complement", which is essentially "invert the number and add 1".

    So, if we have, for simplicity, 8 bit numbers:

    15 is            00001111
    Inverted we get  11110000
    Add one          11110001
    
    17 is            00010001
    
    Ored together    11110001
    

提交回复
热议问题