Ho creato un metodo per convertire un int
in un bitfield (in un elenco) e funziona, ma sono sicuro che ci sia una soluzione più elegante, l'ho appena visto per lungo tempo.Numero intero in bitfield come elenco
Sono curioso, come convertire un int
in un bitfield rappresentato in un list
?
def get(self):
results = []
results.append(1 if (self.bits & 1) else 0)
results.append(1 if (self.bits & 2) else 0)
results.append(1 if (self.bits & 4) else 0)
results.append(1 if (self.bits & 8) else 0)
results.append(1 if (self.bits & 16) else 0)
results.append(1 if (self.bits & 32) else 0)
results.append(1 if (self.bits & 64) else 0)
results.append(1 if (self.bits & 128) else 0)
return results
def set(self, pin, direction):
pin -= 1
if pin not in range(0, 8): raise ValueError
if direction: self.bits |= (2 ** pin)
else: self.bits &=~(2 ** pin)
+1 per piacevoli considerazioni temporizzazione – snugglo
'[123 >> i & 1 per i in range (7, -1, -1)] 'è il più veloce sulla mia macchina. – tMC
@tMC: Ho rifatto i tempi su entrambi i miei PC (Win 7 Ultimate 64bit), in Python 2.7.3 e 3.2.3, e la mia soluzione era sempre più veloce di almeno il 20% (Python 2) e il 45% (Python 3). –