Bitwise negation gives unexpected result

后端 未结 5 1219
情歌与酒
情歌与酒 2021-01-05 07:40

I am trying to write a bitwise calculator in java, something that you could input an expression such as ~101 and it would give back 10 however when i run this code



        
5条回答
  •  没有蜡笔的小新
    2021-01-05 08:15

    If a = ...0000101 (bin) = 5 (dec)

    ~a = ~...0000101(bin) = ...1111010(bin) 
    

    and Java uses "Two's complement" form to represent negative numbers so

    ~a = -6 (dec)
    

    Now difference between Integer.toBinaryString(number) and Integer.toString(number, 2) for negative number is that

    • toBinaryString returns String in "Two's complement" form but
    • toString(number, 2) calculates binary form as if number was positive and add "minus" mark if argument was negative.

    So toString(number, 2) for ~a = -6 will

    1. calculate binary value for 6 -> 0000110,
    2. trim leading zeros -> 110,
    3. add minus mark -> -110.

提交回复
热议问题