1

I'm trying to create an array of bits in python that are two binary numbers into a fixed width.

For eg.

[11,90] ----> 0000101101011010

What I've tried/ Problems I've encountered:

  1. bin(11) => 0b1010 (which is not the fixed width I need)

  2. String manipulation using format '{0:11b}'.format(8) (this works but I'd like to avoid converting to strings and back if I can. It seems like a lot of overhead to do essentially a shift and add)

8
  • Python doesn't support bit arrays. Or what do you mean? Commented Dec 25, 2017 at 0:02
  • 6
    How did you get 0b0000101101011010 from 11 and 90? Commented Dec 25, 2017 at 0:02
  • bin returns a string. I wouldn't worry about the overhead unless you actually see it causing problems, it's unlikely to matter much. If you are worried, then you should build your own lists of True and False, which are as close as you are likely to get to a bit array. '{:0>8b}{:0>8b}'.format(x, y) should be sufficient Commented Dec 25, 2017 at 0:07
  • @Galen I see it now. 11 in binary is 1011, and 00001011 is the first half of the number, 90 is 1011010 and 01011010 is the second half. So it seems as if they want to convert numbers in a list to binary, add 0's to the front until each is 8 bits long, then append them together. Commented Dec 25, 2017 at 0:07
  • 1
    Try a = 11 << 8 | 90, then bin(a) produces 0b101101011010 Commented Dec 25, 2017 at 0:10

2 Answers 2

3

You can use struct:

bin(int.from_bytes(struct.pack('>bb', 11, 90), byteorder='big'))

If you want the leading 0s:

'{:016b}'.format(int.from_bytes(struct.pack('>bb', 11, 90), byteorder='big'))
Sign up to request clarification or add additional context in comments.

Comments

2

Guessing what you want to do, since you're not very detailed on your question, you can use bin(x)[2:] removing the first two characters, then zero fill it with str.zfill(length) and then concatenating your two numbers, like so:

print(bin(11)[2:].zfill(8) + bin(90)[2:].zfill(8))

Will print: 0000101101011010

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.