1

I am trying to convert a binary value to a list with each 1/0 but I get the default binary value and not the list.

I have a string, I convert each character in binary and it gives me an list with a string for each character. Now I am trying to split each string into ints with the value 0/1 but I can't get anything.

# if message = "CC"
message="CC"

# just a debug thing
for c in message:
    asci = ord(c)
    bin = int("{0:b}".format(asci))
    print >> sys.stderr, "For %c, asci is %d and bin is %d" %(c,asci,bin)

c = ["{0:b}".format(ord(c)) for c in message]
# c = ['1000011', '1000011']
bin = [int(c) for c in c]
#bin should be [1,0,0,0,0,1,1,1,0,0,0,0,1,1]
# but I get [1000011, 1000011]
print >> sys.stderr, bin

2 Answers 2

2

If you have this:

c = ['1000011', '1000011']

And you want to achieve this:

[1,0,0,0,0,1,1,1,0,0,0,0,1,1]

You can do:

modified_list=[int(i) for  element in c for i in element]

Or you can use itertools.chain

from itertools import chain
modified_list=list(chain(*c)) 

As you want to join both the list comprehension, you can do it this way:

bin= list( chain( *["{0:b}".format(ord(c)) for c in message] )
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you ! Is there a way to do my two list comprehensions in one line ?
bin = [int(i) for element in ["{0:b}".format(ord(c)) for c in message] for i in element]
0

Try;

bin = [int(x) for s in c for x in s]

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.