464,563 Members | 918 Online
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
5 Replies

 Expert Mod 2.5K+ P: 2,851 Yes. The ascii character code can be converted to base 2. Expand|Select|Wrap|Line Numbers def dec2bin(num):     ''' Convert a decimal integer to base 2.'''     if num == 0:         return ''     num, rem = divmod(num, 2)     return dec2bin(num)+str(rem) Testing: Expand|Select|Wrap|Line Numbers >>> dec2bin(ord('h')) '1101000' >>>  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

 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 >>> num, rem = divmod(100, 2) >>> num 50 >>> rem   >>> num, rem = divmod(1, 2) >>> num   >>> rem 1 >>> 100%2   >>> 1%2 1 >>> divmod(101, 2) (50, 1) >>>  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