Bitwise negation gives unexpected result

后端 未结 5 1218
情歌与酒
情歌与酒 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:19

    The toString() method interprets its argument as a signed value.

    To demonstrate binary operations its better to use Integer.toBinaryString(). It interprets its argument as unsigned, so that ~101 is output as 11111111111111111111111111111010.

    If you want fewer bits of output you can mask the result with &.

提交回复
热议问题