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

后端 未结 7 2063
鱼传尺愫
鱼传尺愫 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:18

    There is also the pure-Python python-bitstring (with Python 3 support).

    0 讨论(0)
  • 2020-12-03 12:24

    The library BitVector is a pure-Python library for this purpose, and should suit the needs you specified.

    0 讨论(0)
  • 2020-12-03 12:29

    I'm surprised that no one has mentioned ints (or I guess long in Python 2). ints can be arbitrarily large, you can use bitwise operators on them, they're fast, and the code looks like bit twiddling code in C (I consider that to be an advantage).

    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.
    

    I've used this for bitvectors hundreds of bits long.

    0 讨论(0)
  • 2020-12-03 12:30

    It has lists, which you can populate with bools:

    [False] * 20
    
    0 讨论(0)
  • 2020-12-03 12:37

    Use struct module.

    0 讨论(0)
  • 2020-12-03 12:38

    The bitarray module does this efficiently with booleans.

    0 讨论(0)
提交回复
热议问题