How to Convert a string into binary

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • HNT20

    How to Convert a string into binary

    Hello All

    i am new to python language. i am working on a gnuradio project where it
    uses python as the primary programming language. i am trying to convert
    a message, text, or numbers into binary code so that i can process it.

    i googled many times and tried many of the answers out there, no luck so
    far.

    is there a way to convert a string into its binary representation of the
    ascii table.??

    an example of what i want would be:

    hi --> 011010000110100 1


    Thanks
    -HNT
  • Felipe Almeida Lessa

    #2
    Re: How to Convert a string into binary

    Em Sáb, 2006-04-15 às 19:25 +0000, HNT20 escreveu:[color=blue]
    > is there a way to convert a string into its binary representation of the
    > ascii table.??[/color]

    I'm very curious... why?

    And no, I don't have the answer.

    --
    Felipe.

    Comment

    • Rune Strand

      #3
      Re: How to Convert a string into binary


      HNT20 wrote:[color=blue]
      > Hello All
      >[/color]

      def ascii_to_bin(ch ar):
      ascii = ord(char)
      bin = []

      while (ascii > 0):
      if (ascii & 1) == 1:
      bin.append("1")
      else:
      bin.append("0")
      ascii = ascii >> 1

      bin.reverse()
      binary = "".join(bin )
      zerofix = (8 - len(binary)) * '0'

      return zerofix + binary



      some_string = 'Time to go now, Rummy?'

      binary = []
      for char in some_string:
      binary.append(a scii_to_bin(cha r))

      print binary
      print " ".join(bina ry)



      some_string = 'Time to go now, Rummy?'

      binary = []
      for char in some_string:
      binary.append(a scii_to_bin(cha r))

      print binary
      print " ".join(bina ry)

      """
      ['01010100', '01101001', '01101101', '01100101', '00100000',
      '01110100', '01101111', '00100000', '01100111', '01101111', '00100000',
      '01101110', '01101111', '01110111', '00101100', '00100000', '01010010',
      '01110101', '01101101', '01101101', '01111001', '00111111']
      01010100 01101001 01101101 01100101 00100000 01110100 01101111 00100000
      01100111 01101111 00100000 01101110 01101111 01110111 00101100 00100000
      01010010 01110101 01101101 01101101 01111001 00111111
      """

      Comment

      • Duncan Booth

        #4
        Re: How to Convert a string into binary

        HNT20 wrote:
        [color=blue]
        > is there a way to convert a string into its binary representation of the
        > ascii table.??
        >
        > an example of what i want would be:
        >
        > hi --> 011010000110100 1[/color]

        Why not just write some code to do it? e.g.
        [color=blue][color=green][color=darkred]
        >>> def b1(n):[/color][/color][/color]
        return "01"[n%2]
        [color=blue][color=green][color=darkred]
        >>> def b2(n):[/color][/color][/color]
        return b1(n>>1)+b1(n)
        [color=blue][color=green][color=darkred]
        >>> def b3(n):[/color][/color][/color]
        return b2(n>>2)+b2(n)
        [color=blue][color=green][color=darkred]
        >>> def b4(n):[/color][/color][/color]
        return b3(n>>4)+b3(n)
        [color=blue][color=green][color=darkred]
        >>> bytes = [ b4(n) for n in range(256)]
        >>> def binstring(s):[/color][/color][/color]
        return ''.join(bytes[ord(c)] for c in s)
        [color=blue][color=green][color=darkred]
        >>> binstring('hi')[/color][/color][/color]
        '01101000011010 01'

        Comment

        • bearophileHUGS@lycos.com

          #5
          Re: How to Convert a string into binary

          If (assuming this is correct, you can do more tests) the given strings
          are many and/or long, this can be a fast version. With Psyco this same
          version can become quite faster.
          Bye,
          bearophile


          from array import array

          class ToBinary(object ):
          """ToBinary : class to convert a given string to a binary string."""
          def __init__(self):
          _nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
          "4":"0100", "5":"0101", "6":"0110", "7":"0111",
          "8":"1000", "9":"1001", "A":"1010", "B":"1011",
          "C":"1100", "D":"1101", "E":"1110", "F":"1111"}
          self._bytes = ["".join(_nibble s[h] for h in "%X"%i).zfill(8 )
          for i in xrange(256)]
          def conv(self, s):
          if s:
          result = [self._bytes[el] for el in array("B", s)]
          result[0] = result[0].lstrip("0")
          return "".join(res ult)
          else:
          return "0"

          # Tests
          Conv2 = ToBinary()
          data = ["", "a", "b", "ab", "hello", "123456789"]
          for s in data:
          print s, Conv2.conv(s)

          Comment

          • Fredrik Lundh

            #6
            Re: How to Convert a string into binary

            "HNT20" <hnt20@msn.co m> wrote:
            [color=blue]
            > i am new to python language. i am working on a gnuradio project where it
            > uses python as the primary programming language. i am trying to convert
            > a message, text, or numbers into binary code so that i can process it.[/color]

            umm. characters and numbers are stored in binary code, inside your com-
            puter. what exactly makes you think you have to convert them to binary
            strings in order to process them ?

            </F>



            Comment

            • HNT20

              #7
              Re: How to Convert a string into binary

              bearophileHUGS@ lycos.com wrote:[color=blue]
              > If (assuming this is correct, you can do more tests) the given strings
              > are many and/or long, this can be a fast version. With Psyco this same
              > version can become quite faster.
              > Bye,
              > bearophile
              >
              >
              > from array import array
              >
              > class ToBinary(object ):
              > """ToBinary : class to convert a given string to a binary string."""
              > def __init__(self):
              > _nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
              > "4":"0100", "5":"0101", "6":"0110", "7":"0111",
              > "8":"1000", "9":"1001", "A":"1010", "B":"1011",
              > "C":"1100", "D":"1101", "E":"1110", "F":"1111"}
              > self._bytes = ["".join(_nibble s[h] for h in "%X"%i).zfill(8 )
              > for i in xrange(256)]
              > def conv(self, s):
              > if s:
              > result = [self._bytes[el] for el in array("B", s)]
              > result[0] = result[0].lstrip("0")
              > return "".join(res ult)
              > else:
              > return "0"
              >
              > # Tests
              > Conv2 = ToBinary()
              > data = ["", "a", "b", "ab", "hello", "123456789"]
              > for s in data:
              > print s, Conv2.conv(s)
              >[/color]

              Thanks you very much, i will give this code a try. i hope it will work.

              Comment

              • HNT20

                #8
                Re: How to Convert a string into binary

                Rune Strand wrote:[color=blue]
                > HNT20 wrote:[color=green]
                >> Hello All
                >>[/color]
                >
                > def ascii_to_bin(ch ar):
                > ascii = ord(char)
                > bin = []
                >
                > while (ascii > 0):
                > if (ascii & 1) == 1:
                > bin.append("1")
                > else:
                > bin.append("0")
                > ascii = ascii >> 1
                >
                > bin.reverse()
                > binary = "".join(bin )
                > zerofix = (8 - len(binary)) * '0'
                >
                > return zerofix + binary
                >
                >
                >
                > some_string = 'Time to go now, Rummy?'
                >
                > binary = []
                > for char in some_string:
                > binary.append(a scii_to_bin(cha r))
                >
                > print binary
                > print " ".join(bina ry)
                >
                >
                >
                > some_string = 'Time to go now, Rummy?'
                >
                > binary = []
                > for char in some_string:
                > binary.append(a scii_to_bin(cha r))
                >
                > print binary
                > print " ".join(bina ry)
                >
                > """
                > ['01010100', '01101001', '01101101', '01100101', '00100000',
                > '01110100', '01101111', '00100000', '01100111', '01101111', '00100000',
                > '01101110', '01101111', '01110111', '00101100', '00100000', '01010010',
                > '01110101', '01101101', '01101101', '01111001', '00111111']
                > 01010100 01101001 01101101 01100101 00100000 01110100 01101111 00100000
                > 01100111 01101111 00100000 01101110 01101111 01110111 00101100 00100000
                > 01010010 01110101 01101101 01101101 01111001 00111111
                > """
                >[/color]
                Thanks very much. this code looks really promising. i will try to
                implement this code and see if i get any luck

                HNT

                Comment

                • HNT20

                  #9
                  Re: How to Convert a string into binary

                  Felipe Almeida Lessa wrote:[color=blue]
                  > Em Sáb, 2006-04-15 às 19:25 +0000, HNT20 escreveu:[color=green]
                  >> is there a way to convert a string into its binary representation of the
                  >> ascii table.??[/color]
                  >
                  > I'm very curious... why?
                  >
                  > And no, I don't have the answer.
                  >[/color]

                  well, once i get the binary representations , i can group the data and
                  modulate it to a higher frequency and transmit it for example, if i am
                  using BPSK modulation, i will then convert each zero into -1 and
                  multiply it with the sin function with the sampling frequency with a
                  hamming window. and so forth. yet, the first step is to have a
                  successful representation of the data.

                  HNT

                  Comment

                  • Terry Reedy

                    #10
                    Re: How to Convert a string into binary


                    "HNT20" <hnt20@msn.co m> wrote in message
                    news:KMb0g.9218 2$9I5.52507@tor nado.ohiordc.rr .com...[color=blue]
                    > i am new to python language. i am working on a gnuradio project where it
                    > uses python as the primary programming language. i am trying to convert
                    > a message, text, or numbers into binary code so that i can process it.[/color]
                    .....[color=blue]
                    > hi --> 011010000110100 1[/color]

                    I would start by making a lookup table to translate the ordinals of ascii
                    chars to binary strings:
                    a2b = ['00000000', '00000001', '00000010', etc ...
                    using something that generates the binary strings (such as that posted).
                    If you don't want any or all of the initial 32 control chars translated,
                    replace the corresponding string with ''.

                    Then your main program is very simple:

                    # given string s
                    binchars = []
                    for c in s: binchars.append (a2b[ord(c)])

                    #if you really then need one long string instead of the list of strings
                    longstring = ''.join(binchar s)
                    #or use any other connector than '', such as ' '.

                    Terry Jan Reedy






                    Comment

                    • Felipe Almeida Lessa

                      #11
                      Re: How to Convert a string into binary

                      Em Sáb, 2006-04-15 às 18:09 -0400, Terry Reedy escreveu:[color=blue]
                      > # given string s
                      > binchars = []
                      > for c in s: binchars.append (a2b[ord(c)])[/color]

                      Faster:

                      binchars = [a2b[ord(c)] for c in s]

                      --
                      Felipe.

                      Comment

                      • John Machin

                        #12
                        Re: How to Convert a string into binary

                        On 16/04/2006 5:25 AM, HNT20 wrote:[color=blue]
                        >
                        > hi --> 011010000110100 1
                        >[/color]

                        This implies that the bits in a byte are transmitted MSB first. I
                        haven't done anything anywhere near this area since about the time that
                        acoustic couplers went the way of buggy whips, but my vague recollection
                        is LSB first.

                        Comment

                        • Jesse Hager

                          #13
                          Re: How to Convert a string into binary

                          The short version:

                          def str2bin(s):
                          return ''.join([''.join(['10'[not (m&ord(x))] for m in
                          (128,64,32,16,8 ,4,2,1)]) for x in s])

                          Notes:

                          Split into 3 lines for newsgroup post, 3rd line is actually the end of
                          the 2nd. It will run as shown above.

                          Returns digits in MSB order, to return LSB first, reverse the order of
                          the bit weights. (1,2,4,8,16,32, 64,128)

                          To support 16-bit Unicode, add powers of two to the bit weights up to 32768.

                          To put a separator between digits for each character put it between
                          first set of empty quote chars. ',' -> '00000000,11111 111'

                          To put a separator between digits of the same character, put it between
                          the second set of empty quotes. '.' -> '0.1.0.1.0.1.0. 1'

                          This is probably slower than one based on lookup tables like the others
                          are proposing.

                          --
                          Jesse Hager
                          email = "wrffruntre@tzn vy.pbz".decode( "rot13")

                          Comment

                          • Grant Edwards

                            #14
                            Re: How to Convert a string into binary

                            On 2006-04-16, John Machin <sjmachin@lexic on.net> wrote:[color=blue]
                            > On 16/04/2006 5:25 AM, HNT20 wrote:[color=green]
                            >>
                            >> hi --> 011010000110100 1
                            >>[/color]
                            >
                            > This implies that the bits in a byte are transmitted MSB first. I
                            > haven't done anything anywhere near this area since about the time that
                            > acoustic couplers went the way of buggy whips, but my vague recollection
                            > is LSB first.[/color]

                            It depends. "Normal" UARTs send LSB first. Some other types of
                            serial links are MSB first.

                            --
                            Grant Edwards
                            grante@visi.com

                            Comment

                            Working...