整数到位域作为列表 [英] Integer to bitfield as a list
本文介绍了整数到位域作为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了一种将 int
转换为位域(在列表中)的方法,并且它可以工作,但是我敢肯定还有更优雅的解决方案-我一直在盯着它会持续很长时间.
I've created a method to convert an int
to a bitfield (in a list) and it works, but I'm sure there is more elegant solution- I've just been staring at it for to long.
我很好奇,如何将 int
转换为 list
中表示的位域?
I'm curious, how would you convert a int
to a bitfield represented in a 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)
推荐答案
这是怎么回事:
def bitfield(n):
return [int(digit) for digit in bin(n)[2:]] # [2:] to chop off the "0b" part
这给你
>>> bitfield(123)
[1, 1, 1, 1, 0, 1, 1]
>>> bitfield(255)
[1, 1, 1, 1, 1, 1, 1, 1]
>>> bitfield(1234567)
[1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1]
这仅适用于正整数.
使用 int()
转换为 int
有点夸张.这要快得多:
Conversion to int
using int()
is a bit overkill here. This is a lot faster:
def bitfield(n):
return [1 if digit=='1' else 0 for digit in bin(n)[2:]]
查看时间:
>>> import timeit
>>> timeit.timeit("[int(digit) for digit in bin(123)[2:]]")
7.895014818543946
>>> timeit.timeit("[123 >> i & 1 for i in range(7,-1,-1)]")
2.966295244250407
>>> timeit.timeit("[1 if digit=='1' else 0 for digit in bin(123)[2:]]")
1.7918431924733795
这篇关于整数到位域作为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文