Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

python - How to convert an integer to a list of bits?

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)

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]

How can I do this both for numbers less then 8 bits and also for larger ones?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For a fixed size of 8 bits:

num = 0x15
out = [1 if num & (1 << (7-n)) else 0 for n in range(8)]

The (1 << (7-n)) creates a single bit mask for a given position, and then bitwise & tests to see if that bit is set in the number. Having n work through 0 to 7 results in all 8 bits in the byte being tested in order.

For arbitrarily sized numbers:

import math
num = 0x715
bits = int(max(8, math.log(num, 2)+1))
out = [1 if num & (1 << (bits-1-n)) else 0 for n in range(bits)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...