How do I represent and work with n-bit vectors in Python?

后端 未结 7 2089
鱼传尺愫
鱼传尺愫 2020-12-03 12:04

In an assignment I am currently working on we need to work with bit vectors, but I am very unsure of how to do this in Python. They should be able to be from 4 bits to 20 bi

相关标签:
7条回答
  • 2020-12-03 12:44

    A bit dated but I'm going to leave another stdlib option here just for comparison sake. It is also easy to do this using the ctypes module.

    For example:

    And is it possible (how?) to express a bit vector of size 20 ? I am thinking of perhaps making a 24 bit / 3 byte vector and ignoring the 4 bits.

    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')
    

    or something more straight forward like this:

    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
    
    0 讨论(0)
提交回复
热议问题