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

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

    The operator | is a "bitwise OR" operator, meaning that every bit in the target is computed as the OR-combination of the corresponding bits in the two operands. This means, that a bit in the result is 1 if any of the two bits in the numbers at the same positions are 1, otherwise 0.

    Clearly, the result depends on the binary representation of the numbers which again depends on the platform.

    Almost all platforms use the Two's complement, which can be thought as a circle of unsigned numbers, in which negative numbers are just in the opposite direction than positive numbers and "wrap around" the circle.

    Unsigned integers:

    enter image description here

    Signed integers:

    enter image description here

    The calculation of your example is as follows.

     17:   00000000 00000000 00000000 00010001
    -15:   11111111 11111111 11111111 11110001
    ------------------------------------------
    -15:   11111111 11111111 11111111 11110001
    

提交回复
热议问题