-1

I am trying to translate code from php to python. I have a list of binary literals -

['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']

This is equal to 0000000000000000000000000000000000000000000000000000010001001100 when concatenated.

int("0000000000000000000000000000000000000000000000000000010001001100",2)

gives 1100

How do i make this from the list. Unable to concatenate binary literals.

3
  • Shouldn't it be 1001001100 when concatenated? Commented Dec 9, 2012 at 22:30
  • 1
    Unstated here is that each piece represents eight bits, and may be missing leading zeros. Commented Dec 9, 2012 at 22:35
  • 0b0 = 00000000 , last two 00000100 , 01001100 Commented Dec 9, 2012 at 22:35

4 Answers 4

1
>>> l = ['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']
>>> int("".join("%02x" % int(x,0) for x in l), 16)
1100

Python understand 0b0101 as a binary literal, so I use int('0b0101', 0) to convert each piece to an int. Then I format it in a convenient format (two digits of hex), concatenate them, and interpret them as a hex integer.

Sign up to request clarification or add additional context in comments.

2 Comments

Where is int(..., 0) documented? Never seen it before.
Right there in the docs: docs.python.org/2/library/functions.html#int "Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16."
1

You need the zfill method to pad your elements with the right quantity of zeros

li = ['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']
zero_padded = [x[2:].zfill(8) for x in li]
print ''.join(zero_padded)

Outputs

0000000000000000000000000000000000000000000000000000010001001100

Comments

0

Just strip off the 0b:

binary = ''.join(x[2:] for x in yourlist)
print binary
print int(binary, 2)

2 Comments

Outputs 588. I need to concatenate and get the ascii value
@AdityaSingh: Your expected output is wrong. You've added a zero somewhere.
0

Is this ugly enough for you:

int(''.join([i for sl in [s[2:].zfill(8) for s in l] for i in sl]),2)

(It seems to work.)

Maybe this is more readable:

l = ['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']
n = 0
for s in l:
    n = n*256 + int(s,2)
print n

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.