我该如何重新present和Python中的n位向量工作? [英] How do I represent and work with n-bit vectors in Python?

查看:258
本文介绍了我该如何重新present和Python中的n位向量工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在赋值我目前工作的,我们需要与位向量工作,但我非常不确定如何做到这一点在Python。它们应该能够从4位到20位。我从来没有与位向量工作过,但我想,一个人会创建您在使用通常的AND / OR / XOR运算操作的无符号字节数组。

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 bits. I have never worked with bit vector before, but I guess that one would one create arrays of unsigned bytes that you manipulated using the usual AND/OR/XOR operations.

重要的限制这里是:我可以不依赖的任何的比标准Python供应的其他库

The important restriction here is: I cannot rely on any libraries other than those supplied with standard Python.

我想我知道我会如何使用C中的8位无符号字节数组做到这一点:
例如把一个归零的数组的第18位为一,我会做这样的事情
my_bit_array [3]&放大器; = 1&下; 2

I think I know how I would do this in C using arrays of 8 bit unsigned bytes: e.g. to turn the 18th bit of a zeroed array into a one, I would do something like my_bit_array[3] &= 1<<2

不过,由于Python是动态类型,没有内置阵列式,我怎么会去的Python的方式这样做呢?

But since Python is dynamically typed and does not have a built-in array type, how would I go about doing this in a pythonic way?

和有可能(如何?)给前preSS大小20位矢量?我想也许让一个24位/ 3字节向量,而忽略了4位。

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.

推荐答案

库的位向量是一个纯Python库用于这一目的的,应该适合你所指定的需求。

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

这篇关于我该如何重新present和Python中的n位向量工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆