Int列表上的Python位操作 [英] Python Bit Operations on a list of Int's
问题描述
我想做的事情不起作用:
整体清单......
What I want to do that does not work: List of ints...
BebossArray=[0 for i in xrange(1024)]
我的位功能(有通常的设置,清除,切换,测试,但这里设置)
My bit functions (There are all the usual set,clear,toggle, test but here is set)
def setBit(dint, offset):
mask = 1 << offset
dint=(dint|mask)
return
所以我想要在列表中的一个整数中设置一个位...
so I would like to set a bit in one of the ints in the list...
setBit(DebossArray[index],3)
这当然不起作用。 setBit中的赋值只是创建一个新对象,DebossArray [index]按预期保持put。所以我认为INT是不可改变的,所以我不能做出改变。
This, of course, does not work. The assignment in setBit just creates a new object and DebossArray[index] stays put as expected. So I get that INT's are immuttable so I can't do a change in place.
我做了什么......(我不喜欢它,但它适用于我的目的)
What I did... (I don't like it but it works for my purposes)
DebossArray=[ctypes.c_int32() for x in xrange(1024)]
和
def setBit(dint, offset):
mask = 1 << offset
dint.value=(dint.value|mask)
return
所以现在
setBit(DebossArray[index],3]
按预期工作,因为ctype.c_int32()是可变的,所以我可以在适当的位置修改它。
works as expect because ctype.c_int32() IS mutable so I can modify it in place.
我是使用2.7但最多滚动3可能会在项目后期发生。我也试图远离
I am using 2.7 but rolling up to 3 will probably happen later in the project.I am also trying to stay away from
DebossArray[index]=setBit(DebossArray[index],3)
构造类型。
更多细节:
在某些地方我有DebossArray [x]而在其他地方我有ButtonArray [x] [y]
More detail: In some places I have DebossArray[x] and in other places I have ButtonArray[x][y]
现在到了这一点;
这样做的正确方法是什么?
And now to the point; What is the correct way to do this?
推荐答案
我想你重复这一点,只需返回结果并重新绑定原始名称:
I think you're over complicating this, just return the result and rebind the original name:
def setBit(dint, offset):
mask = 1 << offset
return dint | mask
r = 0
r = setBit(r, 5)
# 32
你没有真的甚至需要一个功能,你可以做:
You don't really even need a function, you could just do:
i = 0
i |= (1 << 5)
# 32
这篇关于Int列表上的Python位操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!