Change sign using bitwise operators

后端 未结 3 1213
半阙折子戏
半阙折子戏 2021-01-25 19:35

How to change the sign of int using bitwise operators? Obviously we can use x*=-1 or x/=-1. Is there any fastest way of doing this?

I did a sm

3条回答
  •  清酒与你
    2021-01-25 20:12

    The speed difference between non-floating point (e.g. int math) addition/multiplication and bitwise operations is less than negligible on almost all machines.

    There is no general way to turn an n-bit signed integer into its negative equivalent using only bitwise operations, as the negation operation looks like x = (~x) + 1, which requires one addition. However, assuming the signed integer is 32 bit you can probably write a bitwise equation to do this calculation. Note: do not do this.

    The most common, readable way to negate a number is x = -x.

提交回复
热议问题