How do I manipulate bits in Python?

后端 未结 9 1858
借酒劲吻你
借酒劲吻你 2020-12-12 22:37

In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:

unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
相关标签:
9条回答
  • 2020-12-12 23:15

    Some common bit operations that might serve as example:

    def get_bit(value, n):
        return ((value >> n & 1) != 0)
    
    def set_bit(value, n):
        return value | (1 << n)
    
    def clear_bit(value, n):
        return value & ~(1 << n)
    

    Usage e.g.

    >>> get_bit(5, 2)
    True
    >>> get_bit(5, 1)
    False
    >>> set_bit(5, 1)
    7
    >>> clear_bit(5, 2)
    1 
    >>> clear_bit(7, 2)
    3
    
    0 讨论(0)
  • 2020-12-12 23:16

    Omit the 'unsigned long', and the semi-colons are not needed either:

    value = 0xDEADBEEF
    value &= ~(1<<10)
    print value
    "0x%08X" % value
    
    0 讨论(0)
  • 2020-12-12 23:18

    Have you tried copying and pasting your code into the Python REPL to see what will happen?

    >>> value = 0xdeadbeef
    >>> value &= ~(1<<10)
    >>> hex (value)
    '0xdeadbaef'
    
    0 讨论(0)
提交回复
热议问题