代码之家  ›  专栏  ›  技术社区  ›  oligofren

如何在Python中表示和使用n位向量?

  •  6
  • oligofren  · 技术社区  · 15 年前

    在我目前正在做的一个作业中,我们需要使用位向量,但我不确定如何在Python中做到这一点。它们应该能够从4位到20位。我以前从未使用过位向量,但我想应该创建一个无符号字节数组,您可以使用常用的AND/OR/XOR操作来操作它。

    这个 重要限制 任何

    我想我知道如何使用8位无符号字节数组在C中实现这一点: e、 g.要将调零数组的第18位转换为1,我将执行以下操作

    但是,由于Python是动态类型的,并且没有内置的数组类型,我将如何以Python的方式来实现这一点呢?

    7 回复  |  直到 15 年前
        1
  •  10
  •   Boris Verkhovskiy Brian Clapper    4 年前

    图书馆 BitVector 是用于此目的的纯Python库,应该适合您指定的需要。

        2
  •  30
  •   jpkotta    8 年前

    我很惊讶没有人提到 int s(或者我猜是 long 在Python2中)。 int

    x = 0 # empty
    x |= 1<<19 # set bit 19
    x &= ~(1<<19) # clear bit 19
    x ^= 1<<19 # toggle bit 19
    x = ~x # invert *all* bits, all the way to infinity
    mask = ((1<<20)-1) # define a 20 bit wide mask
    x &= mask # ensure bits 20 and higher are 0
    x ^= mask # invert only bits 0 through 19
    
    (x >> 19) & 1 # test bit 19
    (x >> 16) & 0xf # get bits 16 through 20.
    

    我用它来表示数百位长的位向量。

        3
  •  9
  •   ezod    15 年前

    这个 bitarray

        4
  •  7
  •   Ignacio Vazquez-Abrams    15 年前

    [False] * 20
    
        5
  •  3
  •   gruszczy    15 年前

    使用 struct 模块。

        6
  •  2
  •   lonetwin    8 年前

    有点过时了,但为了比较起见,我将在这里留下另一个stdlib选项。使用 ctypes 模块。

    例如:

    有可能(如何)表达一个大小为20的位向量吗? 我想做一个24位/3字节的向量,忽略4位

    class Simple(ctypes.LittleEndianStructure):
        _pack_ = 1
        _fields_ = [
                     ('one', ctypes.c_ubyte, 8),
                     ('two', ctypes.c_ubyte, 8),
                     ('three', ctypes.c_ubyte, 8)
                   ]
    
    s = Simple(0, 2, 256)
    bytearray(s)        # bytearray(b'\x00\x02\x00')
    s = Simple(0, 2, 255)
    bytearray(s)        # bytearray(b'\x00\x02\xff')
    
    class Simple(ctypes.BigEndianStructure):
        _pack_ = 1
        _fields_ = [
                     ('one', ctypes.c_ubyte, 8),
                     ('two', ctypes.c_ubyte, 8),
                     ('three', ctypes.c_ubyte, 8)
                   ]
    
    s = Simple(0, 2, 256)
    bytearray(s)        # bytearray(b'\x00\x02\x00')
    s = Simple(0, 2, 255)
    bytearray(s)        # bytearray(b'\x00\x02\xff')
    
    s.two |= 3
    bytearray(s)        # bytearray(b'\x00\x03\xff')
    

    class bit_vector(Structure):
        _fields_ = [('bits', c_uint32, 24),
                    ('unused', c_uint32, 8),
                    ]
    
    bv = bit_vector()
    # turn on the 18th bit -- being explicit just to demo it
    bv.bits |= int('000000000000000001000000', 2)
    bin(bv.bits)   # 0b1000000
    
        7
  •  1
  •   Janus Troelsen    12 年前

    还有纯Python python-bitstring (支持Python 3)。