Can string formatting be used to convert an integer to its binaryform ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • fdu.xiaojf@gmail.com

    Can string formatting be used to convert an integer to its binaryform ?

    Hi,

    String formatting can be used to converting an integer to its octal or
    hexadecimal form:
    >>a = 199
    >>"%o" % a
    '307'
    >>"%x" % a
    'c7'

    But, can string formatting be used to convert an integer to its binary
    form ?


    Thanks in advance.

    xiaojf
  • flupke

    #2
    Re: Can string formatting be used to convert an integer to its binaryform ?

    fdu.xiaojf@gmai l.com schreef:
    Hi,
    >
    String formatting can be used to converting an integer to its octal or
    hexadecimal form:
    >>>a = 199
    >>>"%o" % a
    '307'
    >>>"%x" % a
    'c7'
    >
    But, can string formatting be used to convert an integer to its binary
    form ?
    >
    >
    Thanks in advance.
    >
    xiaojf
    I don't actually know how to do it with string formatting but you can
    create a simple function to do it.
    Here's an example:


    Regards,
    Benedict

    Comment

    • Mirco Wahab

      #3
      Re: Can string formatting be used to convert an integer to its binaryform ?

      Thus spoke fdu.xiaojf@gmai l.com (on 2006-09-28 09:10):
      String formatting can be used to converting an integer to its octal or
      hexadecimal form:
      >>a = 199
      >>"%o" % a
      '307'
      >>"%x" % a
      'c7'
      >
      But, can string formatting be used to convert an integer to its binary
      form ?
      I didn't fell over this problem so far but
      I *would* have expected to find something
      like a 'pack' operator (as in Perl).

      And voilá, there is (even basically identical to Perl):

      from struct import *

      a = 199
      a_bin_str = pack('L', a)



      Regards

      Mirco

      Comment

      • Gabriel Genellina

        #4
        Re: Can string formatting be used to convert an integer to itsbinary form ?

        At Thursday 28/9/2006 05:22, Mirco Wahab wrote:
        String formatting can be used to converting an integer to its octal or
        hexadecimal form:
        >>a = 199
        >>"%o" % a
        '307'
        >>"%x" % a
        'c7'

        But, can string formatting be used to convert an integer to its binary
        form ?
        >
        a = 199
        a_bin_str = pack('L', a)
        Notice that the OP was looking for another thing, given the examples.
        Perhaps a better wording would have been "how to convert an integer
        to its base-2 string representation" .


        Gabriel Genellina
        Softlab SRL





        _______________ _______________ _______________ _____
        Preguntá. Respondé. Descubrí.
        Todo lo que querĂ­as saber, y lo que ni imaginabas,
        está en Yahoo! Respuestas (Beta).
        ¡Probalo ya!


        Comment

        • Mirco Wahab

          #5
          Re: Can string formatting be used to convert an integer to its binaryform ?

          Thus spoke Gabriel Genellina (on 2006-09-28 11:05):
          At Thursday 28/9/2006 05:22, Mirco Wahab wrote:
          But, can string formatting be used to convert an integer to its binary
          form ?
          >>
          > a = 199
          > a_bin_str = pack('L', a)
          >
          Notice that the OP was looking for another thing, given the examples.
          Perhaps a better wording would have been "how to convert an integer
          to its base-2 string representation" .
          Yes, you are right. The OP looks for a
          'binary (bit) representation ..."
          I admit I didn't find out how to format
          a value into a bit string in Python.

          In Perl, this would be a no-brainer:

          $var = 199;
          $str = sprintf "%0*b", 32, $var;

          and str would contain 000000000000000 000000000110001 11
          on a intel machine.

          But where is the %b in Python?

          Regards & Thanks

          Mirco

          Comment

          • bearophileHUGS@lycos.com

            #6
            Re: Can string formatting be used to convert an integer to its binary form ?

            Mirco Wahab:
            But where is the %b in Python?
            Python doesn't have that. You can convert the number to a hex, and then
            map the hex digitds to binary strings using a dictionary, like this:


            Bye,
            bearophile

            Comment

            • Frederic Rentsch

              #7
              Re: Can string formatting be used to convert an integer to its binaryform ?

              bearophileHUGS@ lycos.com wrote:
              Mirco Wahab:
              >
              >But where is the %b in Python?
              >>
              >
              Python doesn't have that. You can convert the number to a hex, and then
              map the hex digitds to binary strings using a dictionary, like this:

              >
              Bye,
              bearophile
              >
              >
              Good idea, but shorter with ->

              >>import SE
              >>Int_To_Bina ry = SE.SE (SE.SE ('0=0000 1=0001 2=0010 3=0011 4=0100
              5=0101 6=0110 7=0111 8=1000 9=1001 A=1010 a=1010 B=1011 b=1011 C=1100
              c=1100 D=1101 d=1101 E=1110 e=1110 F=1111 f=1111')
              >>Int_To_Bina ry ('%x' % 1234567890')
              '01001001100101 100000001011010 010'
              >>Int_To_Binary .save ('se_definition _files/int_to_binary.s e')
              >>SE.SE ('se_definition _files/int_to_binary.s e') ('%X' % 987654321)
              '00111010110111 100110100010110 001'


              Frederic

              Comment

              • Mirco Wahab

                #8
                Re: Can string formatting be used to convert an integer to its binaryform ?

                Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
                bearophileHUGS@ lycos.com wrote:
                >Mirco Wahab:
                >>
                >>But where is the %b in Python?
                >>
                >Python doesn't have that. ...
                >http://aspn.activestate.com/ASPN/Coo.../Recipe/440528
                >
                Good idea, but shorter with ->

                SE.SE ('se_definition _files/int_to_binary.s e') ('%X' % 987654321)
                '00111010110111 100110100010110 001'
                I don't really understand here:

                - why doesn't have Python such a simple and useful thing as to_binstr(...)
                even C++ has one built in,
                #include <iostream>
                #include <bitset>

                int somefunc()
                {
                int val = 199;
                std::cout << std::bitset<32> ( val );
                ...

                - why would you favor such complicated solutions
                for this (as posted), when you can have this
                in one line, e.g.:

                def int2bin(num, width=32):
                return ''.join(['%c'%(ord('0')+ bool((1<<k)&num )) for k in range((width-1),-1,-1)])

                (including a string with specifier,this is what I came up with after
                looking up some Python docs - maybe you can straighten this a bit ...)

                -- but my goggles might be biased,
                I don't really emphasize the "Python way" ;-)

                Regards and thanks

                Mirco

                Comment

                • Marc 'BlackJack' Rintsch

                  #9
                  Re: Can string formatting be used to convert an integer to its binary form ?

                  In <efhdt1$9a1$1@m lucom4.urz.uni-halle.de>, Mirco Wahab wrote:
                  Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
                  >bearophileHUGS@ lycos.com wrote:
                  >>Mirco Wahab:
                  >>>
                  >>>But where is the %b in Python?
                  >>>
                  >>Python doesn't have that. ...
                  >>http://aspn.activestate.com/ASPN/Coo.../Recipe/440528
                  >>
                  >Good idea, but shorter with ->
                  >http://cheeseshop.python.org/pypi/SE/2.2%20beta
                  >SE.SE ('se_definition _files/int_to_binary.s e') ('%X' % 987654321)
                  >'0011101011011 110011010001011 0001'
                  >
                  I don't really understand here:
                  >
                  - why doesn't have Python such a simple and useful thing as to_binstr(...)
                  Maybe simple, but useful? And if you really need this it's simple to
                  implement or look up in the cook book.
                  - why would you favor such complicated solutions
                  for this (as posted), when you can have this
                  in one line, e.g.:
                  >
                  def int2bin(num, width=32):
                  return ''.join(['%c'%(ord('0')+ bool((1<<k)&num )) for k in range((width-1),-1,-1)])
                  Yeah, I wonder why not everybody sees the beauty in this cool and
                  straightforward one liner. ;-)

                  Ciao,
                  Marc 'BlackJack' Rintsch

                  Comment

                  • Fredrik Lundh

                    #10
                    Re: Can string formatting be used to convert an integer to its binaryform ?

                    Mirco Wahab wrote:
                    - why doesn't have Python such a simple and useful thing as to_binstr(...)
                    useful? really? for what?

                    </F>

                    Comment

                    • Mirco Wahab

                      #11
                      Re: Can string formatting be used to convert an integer to its binaryform ?

                      Thus spoke Marc 'BlackJack' Rintsch (on 2006-09-28 23:38):
                      > def int2bin(num, width=32):
                      > return ''.join(['%c'%(ord('0')+ bool((1<<k)&num )) for k in range((width-1),-1,-1)])
                      >
                      Yeah, I wonder why not everybody sees the beauty in this cool and
                      straightforward one liner. ;-)
                      Right. I see this is BS, maybe lots of these lines exist already,
                      one could come up with (sorted by obfuscation, descending):

                      def int2bin(num, width=32):
                      # return ''.join( [chr(ord('0')+bo ol(1<<k & num))for k in range(width-1,-1,-1)] )
                      # return ''.join( map(lambda k:str(num>>k & 1),range(width-1, -1, -1)) )
                      # return ''.join( [str(num>>k & 1)for k in range(width-1, -1, -1)] )

                      But after some thinking, I thought about discussing this one:

                      def i2b(num, width):
                      return str(1 & num>>(width-1)) + i2b(num, width-1) if width else ''

                      which is the shortest ;-)

                      (Sorry but I'm more or less a newbie, maybe this is BS too ...)

                      Regards

                      Mirco

                      Comment

                      • Mirco Wahab

                        #12
                        Re: Can string formatting be used to convert an integer to its binaryform ?

                        Thus spoke Fredrik Lundh (on 2006-09-28 23:35):
                        Mirco Wahab wrote:
                        >
                        >- why doesn't have Python such a simple and useful thing as to_binstr(...)
                        >
                        useful? really? for what?
                        I don't really know, but according to google,
                        people often ask exactly for that and there
                        is no reason at all why one shouldn't expect
                        to get a /bit string/ from "%b" %.

                        So if people think it's badly needed, how
                        couldn't it be *not* useful then? ;-)

                        It feels to me (as it does sometimes
                        when diving into Python, to be honest)
                        simply as a shortcoming, - and the ter-
                        nary operator included in 2.5 was
                        imho a huge step forward, next will
                        be mutable strings and arrays will be
                        'called arrays' somewhere ... ;-)

                        (maybe somebody reverses the -v/-V switch too, hey)

                        Regards

                        Mirco

                        Comment

                        • bearophileHUGS@lycos.com

                          #13
                          Re: Can string formatting be used to convert an integer to its binary form ?

                          Frederic Rentsch:
                          Good idea, but shorter with ->
                          >>SE.SE ('se_definition _files/int_to_binary.s e') ('%X' % 987654321)
                          '00111010110111 100110100010110 001'
                          Note that your version keeps the leading zeros.
                          Have you tested the relative speeds too?
                          (I'll probably have to learn to use SE.)

                          Bye,
                          bearophile

                          Comment

                          • Lawrence D'Oliveiro

                            #14
                            Re: Can string formatting be used to convert an integer to its binary form ?

                            In message <1159455615.546 936.83170@m7g20 00cwm.googlegro ups.com>, bearophileHUGS@ lycos.com wrote:
                            Mirco Wahab:
                            >But where is the %b in Python?
                            >
                            Python doesn't have that. You can convert the number to a hex, and then
                            map the hex digitds to binary strings using a dictionary, like this:
                            http://aspn.activestate.com/ASPN/Coo.../Recipe/440528
                            How about this: (where n is the integer you want to convert):

                            "".join([["0", "1"][(1 << i & n) != 0] for i in range(int(math. ceil(math.log(n , 2))) - 1, -1, -1)])

                            Comment

                            • Lawrence D'Oliveiro

                              #15
                              Re: Can string formatting be used to convert an integer to its binary form ?

                              In message <efhril$nrm$1@l ust.ihug.co.nz> , I wrote:
                              "".join([["0", "1"][(1 << i & n) != 0] for i in range(int(math. ceil(math.log(n , 2))) - 1, -1, -1)])
                              Uh, make that

                              "".join([["0", "1"][(1 << i & n) != 0] for i in range(int(math. floor(math.log( n, 2))), -1, -1)])

                              Need to check those corner cases. :)

                              Comment

                              Working...