How do I do a bitwise Not operation in Python?

后端 未结 5 1879
自闭症患者
自闭症患者 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:47

    Python bitwise '~' operator invert all bits of integer but we can't see native result because all integers in Python has signed representation.

    Indirectly we can examine that:

    >>> a = 65
    >>> a ^ ~a
    -1
    

    Or the same:

    >>> a + ~a
    -1
    

    Ther result -1 means all bits are set. But the minus sign ahead don't allow us to directly examine this fact:

    >>> bin(-1)
    '-0b1'
    

    The solution is simple: we must use unsigned integers. First way is to import 'numpy' or 'ctypes' modules wich both support unsigned integers. But numpy more simplest using than ctypes (at least for me):

    import numpy as np
    a = np.uint8(0b1100)
    y = ~x
    

    Check result:

    >>> bin(x)
    '0b1100'
    >>> bin(y)
    '0b11110011'
    

    And finally check:

    >>> x + y
    255
    

    Unsigned integer '255' for 8-bits integers (bytes) mean the same as '-1' becouse has all bits set to 1. Make sure:

    >>> np.uint8(-1)
    255
    

    ----------

    And another simplest solution, not quite right, but if you want to include additional modules, you can invert all bits with XOR operation, where second argument has all bits are set to 1:

    a = 0b1100
    b = a ^ 0xFF
    

    This operation will also drop most significant bit of signed integer and we can see result like this:

    >>> print('{:>08b}'.format(a))
    00001100
    >>> print('{:>08b}'.format(b))
    11110011
    

    ----------

    Finally solution contains one more operation and therefore is not optimal:

    >>> b = ~a & 0xFF
    >>> print('{:>08b}'.format(b))
    11110011
    

提交回复
热议问题