Convert a binary to an array with each binary numb

2019-02-28 17:08发布

问题:

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

回答1:

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] )


回答2:

Try;

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