1

i'm using this line to convert Ascii string into binary string:

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

Characters are converted in a 7-bit format (c --> 1100011) Numbers are converted in a 6-bit format (2 --> 110010) I need numbers converted in a 7-bit format (Adding a 0 as MSB, maybe so 2 is 0110010), any idea?

Teo Albano
  • 183
  • 1
  • 1
  • 8
  • Check this out: http://stackoverflow.com/questions/7396849/convert-binary-to-ascii-and-vice-versa-python. You can always add a 0 if you want. – gplayer Oct 19 '15 at 08:37

2 Answers2

2

in case your input is a string, this

format(ord('2'),'07b')

always produces a 7-bit output, e.g.

'0110010'

If you ignore the type of the input in advance (i.e. string or integer)

format(ord(n) if isinstance(n, str) else n,'07b')

for n = '2' produces

'0110010'

whereas for n = 2 it produces

'0000010'

the difference lies in the fact that '2' is a string, and the representation of '2' has the value 50 (decimal)

In case you want a unique binary code for both chars and numbers (for example giving numbers the same code as chars)

format(ord(n) if isinstance(n, str) else n+ord('0'),'07b')

which now produces

'0110010'

for both n = '2' and n = 2

Does it make sense? :)

Pynchia
  • 10,996
  • 5
  • 34
  • 43
0
message=(''.join('0'+format(ord(x), 'b') for x in message))
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69