How do I do a bitwise Not operation in Python?

后端 未结 5 1871
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 23:26

    The problem with using ~ in Python, is that it works with signed integers. This is also the only way that really makes sense unless you limit yourself to a particular number of bits. It will work ok with bitwise math, but it can make it hard to interpret the intermediate results.

    For 4 bit logic, you should just subtract from 0b1111

    0b1111 - 0b1100  # == 0b0011
    

    For 8 bit logic, subtract from 0b11111111 etc.

    The general form is

    def bit_not(n, numbits=8):
        return (1 << numbits) - 1 - n
    

提交回复
热议问题