Pregunta

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)

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

and

def setBit(dint, offset):
mask = 1 << offset
dint.value=(dint.value|mask)
return

so now

setBit(DebossArray[index],3]

works as expect because ctype.c_int32() IS mutable so I can modify it in place.

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)

type of construct.

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?

¿Fue útil?

Solución

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

Otros consejos

Use a class like this:

class BebossArray(object):
    def __init__(self):
        self._l = [0 for i in xrange(1024)]

    def setBit(self, index, offset):
        self._l[index] = (self._l[index]|1 << offset) 

Or just make setBit accept a list, index, and offset and replace the value at the index with a new value.

Do you mean something like this?

DebossArray = [0 for i in xrange(4)]

def setBit(dint, index, offset):
    dint[index] |= 1 << offset

print DebossArray  # [0, 0, 0, 0]
setBit(DebossArray, 2, 3)
print DebossArray  # [0, 0, 8, 0]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top