how to convert a string to binary ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • moroccanplaya
    New Member
    • Jan 2011
    • 80

    how to convert a string to binary ?

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

    string = "h"

    h in binary = 01001000
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Yes. The ascii character code can be converted to base 2.
    Code:
    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:
    Code:
    >>> dec2bin(ord('h'))
    '1101000'
    >>>

    Comment

    • moroccanplaya
      New Member
      • Jan 2011
      • 80

      #3
      hi thanks for the help, can you explain how it works i dont really get it

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        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.

        Code:
        >>> num, rem = divmod(100, 2)
        >>> num
        50
        >>> rem
        0
        >>> num, rem = divmod(1, 2)
        >>> num
        0
        >>> rem
        1
        >>> 100%2
        0
        >>> 1%2
        1
        >>> divmod(101, 2)
        (50, 1)
        >>>

        Comment

        • moroccanplaya
          New Member
          • Jan 2011
          • 80

          #5
          thanks, and if you want to convert back would you just use binascii

          Comment

          • rdrewd
            New Member
            • Sep 2007
            • 2

            #6
            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:

            The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...
            Last edited by rdrewd; Apr 27 '12, 09:43 PM. Reason: Add link to function documentation.

            Comment

            Working...