How do I do a bitwise Not operation in Python?

后端 未结 5 1870
自闭症患者
自闭症患者 2020-12-05 23:10

In order to test building an Xor operation with more basic building blocks (using Nand, Or, and And in my case) I need to be able to do a Not operation. The built-in n

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 23:28

    The general form given by John La Rooy, can be simplified in this way (python == 2.7 and >=3.1):

    def bit_not(n):
        return (1 << n.bit_length()) - 1 - n
    

提交回复
热议问题