By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,563 Members | 918 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,563 IT Pros & Developers. It's quick & easy.

how to convert a string to binary ?

P: 80
is it possible to convert a string to an ascii binary representation for example

string = "h"

h in binary = 01001000
Apr 11 '12 #1
Share this Question
Share on Google+
5 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
Yes. The ascii character code can be converted to base 2.
Expand|Select|Wrap|Line Numbers
  1. def dec2bin(num):
  2.     ''' Convert a decimal integer to base 2.'''
  3.     if num == 0:
  4.         return ''
  5.     num, rem = divmod(num, 2)
  6.     return dec2bin(num)+str(rem)
Testing:
Expand|Select|Wrap|Line Numbers
  1. >>> dec2bin(ord('h'))
  2. '1101000'
  3. >>> 
Apr 11 '12 #2

P: 80
hi thanks for the help, can you explain how it works i dont really get it
Apr 11 '12 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Short version - the function uses recursion to "build" a string representation. The function returns when "num" becomes 0. Built-in function divmod returns a tuple of numbers representing the division of "num" and 2 and the modulo of "num" and 2.

Expand|Select|Wrap|Line Numbers
  1. >>> num, rem = divmod(100, 2)
  2. >>> num
  3. 50
  4. >>> rem
  5.  
  6. >>> num, rem = divmod(1, 2)
  7. >>> num
  8.  
  9. >>> rem
  10. 1
  11. >>> 100%2
  12.  
  13. >>> 1%2
  14. 1
  15. >>> divmod(101, 2)
  16. (50, 1)
  17. >>> 
Apr 11 '12 #4

P: 80
thanks, and if you want to convert back would you just use binascii
Apr 12 '12 #5

P: 2
ord('h') gives you the integer value of the ASCII code for 'h'. (Longer story and potentially much bigger integer values for a unicode character). bin(i) will convert an integer to a bitstring.

>>> bin(ord('h'))
'0b1101000'

Note that there's a 0b prefix to mark the bit string as a bit string and that leading 0 bits are suppressed.
>>> print len(bin(ord('h')))
9

bin is new in Python 2.6, so if you have an older Python version, you may want to stick with the binary gymnastics of that recursive solution.

The inverse of ord is chr:

>>> chr(0b1101000)
'h'

Documentation of standard functions:

http://docs.python.org/library/functions.html
Apr 27 '12 #6

Post your reply

Sign in to post your reply or Sign up for a free account.