本文介绍了如何在Python中将整数转换为位列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有比当前方法更好的方法.

I would like to know if there is a better way to do this than my current method.

我试图将整数表示为位列表,并且仅当整数为<时才将其填充为8位. 128 :

I'm trying to represent an integer as a list of bits and left pad it to 8 bits only if the integer is < 128:

Example input: 0x15
Desired output: [0, 0, 0, 1, 0, 1, 0, 1]

我通过以下方式进行操作:

I do it in the following way:

input = 0x15
output = deque([int(i) for i in list(bin(input))[2:]])
while len(output) != 8:
    output.appendleft(0)

在python中有更好的方法吗?

Is there a better way to do this in python?

我想将任何整数转换为二进制列表.仅当数字需要少于8位表示时,才应填充到8.

I would like to convert any integer to a binary-list. Pad to 8 only if the number requires less than 8 bits to represent.

Another Example input: 0x715
Desired output: [1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]

推荐答案

input = 0x15

output = [int(x) for x in '{:08b}'.format(input)]

{0:0=8b}'.format(0x15)binary格式表示您的input,其中0 padding为8位数字,然后使用列表推导来创建位列表.

{0:0=8b}'.format(0x15) represents your input in binary format with 0 padding to 8 digits, then using list comprehension to create a list of bits.

或者,您可以使用map函数:

Alternatively, you can use map function:

output = map(int, [x for x in '{:08b}'.format(0x15)])

可变位宽,

如果要使位数可变,这是一种方法:

If you want to make number of bits variable, here is one way:

width = 8 #8bit width
output = [int(x) for x in '{:0{size}b}'.format(0x15,size=width)]
output = map(int, [x for x in '{:0{size}b}'.format(0x15,size=width)])

这已在Python 2.7中进行了测试

This was tested in Python 2.7

这篇关于如何在Python中将整数转换为位列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:37