-1

I have a string I need to convert into a binary. I tried this:

bin = ''.join(format(ord(x), 'b') for x in strr)

But the result is the wrong length, because Python doesn't keep leading zeros. For instance instead of 01110100 it outputs 1110100.

This method:

temp = '{0:08b}'.format(frame)

doesn't work with strings.

How can I convert a string to binary correctly?

EDIT:

Sample Input: 'test'

Desired Output: '1110100011001010111001101110100'

dimo414
  • 47,227
  • 18
  • 148
  • 244
veitr
  • 111
  • 10
  • 3
    What is "binary view" supposed to mean? – Ignacio Vazquez-Abrams May 21 '15 at 05:04
  • What is your expect output for input `'74 65 73 74' `? – mhawke May 21 '15 at 05:09
  • binary view - 0 an 1. Hex view (74 65 73 74) might be unwanted in my question. – veitr May 21 '15 at 05:21
  • 1
    This is not a duplicate of that, @BurhanKhalid. OP here already knows how to format as binary: the question seems to be how to format as zero-padded 8-bit strings. – Adam Smith May 21 '15 at 05:21
  • try this test=74657374 bin(test)[2:] – Ajay May 21 '15 at 05:22
  • @Ajay, thank you for your help, Adam Smith has already helped me. By the way, your method also has the same problem: the result of bin(74) will be '0b1001010', but the correct output is '0b01001010' – veitr May 21 '15 at 05:28
  • There are [any](http://stackoverflow.com/q/18815820/113632) [number](http://stackoverflow.com/q/8553310/113632) of [existing](http://stackoverflow.com/q/11599226/113632) [questions](http://stackoverflow.com/q/7396849/113632) covering this (including the zero padding requirement). – dimo414 May 21 '15 at 06:12

1 Answers1

2

I'm not sure this is doing what you need it to do. How about this instead:

''.join("{:08b}".format(int(num, 16)) for num in strr.split())

DEMO

In [34]: strr
Out[34]: '74 65 73 74'

In [35]: ''.join("{:08b}".format(int(num, 16)) for num in strr.split())
Out[35]: '01110100011001010111001101110100'

If your text is REALLY ordinal-encoded hex, then you've got a really funky way of storing data but you could do:

''.join("{:08b}".format(ord(num)) for num in strr

DEMO

In [42]: strr
Out[42]: '74 65 73 74'

In [43]: ''.join("{:08b}".format(ord(num)) for num in strr)
Out[43]: '0011011100110100001000000011011000110101001000000011011100110011001000000011011100110100'
Adam Smith
  • 52,157
  • 12
  • 73
  • 112