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

前端 未结 6 1769
野的像风
野的像风 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:12

    It's just doing the operation on the binary representations of your numbers. In your case, that appears to be two's complement.

     17 -> 00010001
    -15 -> 11110001
    

    As you can see, the bitwise OR of those two numbers is still -15.

    In your comments above, you indicated that you tried this with the two's complement representations, but you must have done something wrong. Here's the step by step:

     15 ->  00001111      // 15 decimal is 00001111 binary
    -15 -> ~00001111 + 1  // negation in two's complement is equvalent to ~x + 1
    -15 ->  11110000 + 1  // do the complement
    -15 ->  11110001      // add the 1
    

提交回复
热议问题