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
  • Gabriel Genellina

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

    At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote:
    >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)])
    Uhm... so to generate a binary string you have to import the math
    module, convert the integer to float, compute a non-standard
    logarithm, and then...
    What if n<=0?
    Too much, don't you think? :)


    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

    • George Sakkis

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

      Gabriel Genellina wrote:
      At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote:
      >
      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)])
      >
      Uhm... so to generate a binary string you have to import the math
      module, convert the integer to float, compute a non-standard
      logarithm, and then...
      What if n<=0?
      Too much, don't you think? :)
      Having recently discovered the joy of obfuscated python thanks to the
      Code Golf challenges, here's the shortest non-recursive function I came
      up with (all integers, signed):

      f=lambda n:'-'[:n<0]+''.join(str(m& 1)for m in iter(
      lambda x=[abs(n)]:(x[0],x.__setitem__( 0,x[0]>>1))[0],0))[::-1]or'0'

      Any takers ? ;-)

      George

      Comment

      • MonkeeSage

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

        So far as unobfuscated versions go, how about the simple:

        def to_bin(x):
        out = []
        while x 0:
        out.insert(0, str(x % 2))
        x = x / 2
        return ''.join(out)

        Regards,
        Jordan

        Comment

        • Steve Holden

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

          MonkeeSage wrote:
          So far as unobfuscated versions go, how about the simple:
          >
          def to_bin(x):
          out = []
          while x 0:
          out.insert(0, str(x % 2))
          x = x / 2
          return ''.join(out)
          >
          Regards,
          Jordan
          >
          >>to_bin(0)
          ''

          6/10: try harder :)

          regards
          Steve
          --
          Steve Holden +44 150 684 7255 +1 800 494 3119
          Holden Web LLC/Ltd http://www.holdenweb.com
          Skype: holdenweb http://holdenweb.blogspot.com
          Recent Ramblings http://del.icio.us/steve.holden

          Comment

          • Paul Rubin

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

            "MonkeeSage " <MonkeeSage@gma il.comwrites:
            def to_bin(x):
            out = []
            while x 0:
            out.insert(0, str(x % 2))
            x = x / 2
            return ''.join(out)
            That returns the empty string for x=0. I'm not sure if that's a bug
            or a feature.

            It also returns the empty string for x < 0, probably a bug.

            It will break in Python 3, where 1 / 2 == 0.5.

            Here's yet another version:

            def to_bin(n):
            if n < 0: return '-' + to_bin(-n)
            if n==0: return '0'
            return ''.join(
            ("0000", "0001", "0010", "0011",
            "0100", "0101", "0110", "0111",
            "1000", "1001", "1010", "1011",
            "1100", "1101", "1110", "1111",)[int(d,16)] \
            for d in '%x'%n).lstrip( '0')

            Comment

            • George Sakkis

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

              Steve Holden wrote:
              MonkeeSage wrote:
              So far as unobfuscated versions go, how about the simple:

              def to_bin(x):
              out = []
              while x 0:
              out.insert(0, str(x % 2))
              x = x / 2
              return ''.join(out)

              Regards,
              Jordan
              >>to_bin(0)
              ''
              >
              6/10: try harder :)
              Ok, how about a fast *and* readable version? Works for non-negatives,
              but negatives are trivial to add if necessary:

              from array import array

              def fast2bin(n):
              s = array('c')
              while n>0:
              s.append('01'[n&1])
              n >>= 1
              s.reverse()
              return s.tostring() or '0'

              try: import psyco
              except ImportError: pass
              else: psyco.bind(fast 2bin)


              George

              Comment

              • MonkeeSage

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

                Steve Holden wrote:
                >>to_bin(0)
                ''
                Doh! Oh, yeah...that! ;)

                OK...

                def to_bin(x):
                out=[]
                while x 0:
                out.insert(0, str(x % 2))
                x /= 2
                else:
                out.append(str( x))
                return ''.join(out)

                Regards,
                Jordan

                Comment

                • Steve Holden

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

                  MonkeeSage wrote:
                  Steve Holden wrote:
                  >
                  > >>to_bin(0)
                  >>''
                  >
                  >
                  Doh! Oh, yeah...that! ;)
                  >
                  OK...
                  >
                  def to_bin(x):
                  out=[]
                  while x 0:
                  out.insert(0, str(x % 2))
                  x /= 2
                  else:
                  out.append(str( x))
                  return ''.join(out)
                  >
                  It's an often-missed and almost invariably untested corner case that
                  one's first attempt to solve the problem usually rids one of. I have
                  written binary format code about thirteen times in a lifetime of
                  programming so it was easy for me to spot. You'll never make *that*
                  mistake again ;-)

                  Unfortunately forty years of programming experience has taught me that
                  there's an essentially infinite supply of mistakes to make ... your
                  mistakes just get smarter most of the time.

                  regards
                  Steve
                  --
                  Steve Holden +44 150 684 7255 +1 800 494 3119
                  Holden Web LLC/Ltd http://www.holdenweb.com
                  Skype: holdenweb http://holdenweb.blogspot.com
                  Recent Ramblings http://del.icio.us/steve.holden

                  Comment

                  • Frederic Rentsch

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

                    bearophileHUGS@ lycos.com wrote:
                    Frederic Rentsch:
                    >
                    >Good idea, but shorter with ->
                    > >>SE.SE ('se_definition _files/int_to_binary.s e') ('%X' % 987654321)
                    >'0011101011011 110011010001011 0001'
                    >>
                    >
                    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
                    >
                    >
                    If you say speed, I presume you mean speed of execution. No I have not
                    tested that. I know it can't be fast on a test bench. After all, SE is
                    written in Python. I did a first version fifteen years ago in C, am
                    still using it today on occasion and it runs much, much faster than this
                    Python SE. This SE here could be done in C if it passes the test of
                    acceptance.
                    Professionals need to measure execution speed as a part of
                    documenting their products. I am not a professional and so I am free to
                    define my own scale of grades: A (fast enough) and F (not fast enough).
                    I have yet to encounter a situation where SE gets an F. But that says
                    less about SE than about my better knowledge which prevents me from
                    using SE to, say, change colors in a 50 Mb bitmap. Obviously, "fast
                    enough" and "not fast enough" pertains not to code per se, but to code
                    in a specific situation. So, as the saying goes: the proof of the
                    pudding ...
                    Another kind of speed is production speed. I do believe that SE
                    rather excels on that side. I also believe that the two kinds of speed
                    are economically related by the return-on-investment principle.
                    The third kind of speed is learning speed. SE is so simple that it
                    has no technical learning curve to speak of. It's versatility comes from
                    a wealth of application techniques that invite exploration, invention
                    even. Take leading zeroes:

                    Leading zeroes can be stripped in a second pass if they are made
                    recognizable in the first pass by some leading mark that is not a zero
                    or a one. ([^01]; I use "@" in the following example). To purists this
                    may seem hackish. So it is! And what's wrong with that if it leads to
                    simpler solutions?
                    >>Hex_To_Bina ry = 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 | ~[^01]0*~=')
                    >>Hex_To_Binary .set (keep_chain = 1)
                    >>Hex_To_Bina ry ('@%x' % 1234567890)
                    '10010011001011 000000010110100 10'
                    >>Hex_To_Binary .show ()
                    .... snip ...

                    Data Chain
                    ----------------------------------------------------------------------------------
                    @499602d2
                    0
                    --------------------------------------------------------------------------------
                    @01001001100101 100000001011010 010
                    1
                    --------------------------------------------------------------------------------
                    100100110010110 000000101101001 0
                    ----------------------------------------------------------------------------------


                    Frederic

                    (The previously posted example "Int_To_Bin ary = SE.SE (SE.SE ( ..." was
                    a typo, or course. One (SE.SE does it. Sorry about that.)

                    Comment

                    • Simon Brunning

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

                      On 9/29/06, Steve Holden <steve@holdenwe b.comwrote:
                      Unfortunately forty years of programming experience has taught me that
                      there's an essentially infinite supply of mistakes to make ... your
                      mistakes just get smarter most of the time.
                      +1 QOTW.

                      --
                      Cheers,
                      Simon B,
                      simon@brunningo nline.net

                      Comment

                      • Neil Cerutti

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

                        On 2006-09-29, Steve Holden <steve@holdenwe b.comwrote:
                        MonkeeSage wrote:
                        >So far as unobfuscated versions go, how about the simple:
                        >>
                        >def to_bin(x):
                        > out = []
                        > while x 0:
                        > out.insert(0, str(x % 2))
                        > x = x / 2
                        > return ''.join(out)
                        >>
                        >Regards,
                        It was surprising that
                        >>i = int("111010101" , 2)
                        is a one-way operation.
                        >>s = str(i, 2)
                        Traceback (most recent call last):
                        File "<stdin>", line 1, in ?
                        TypeError: str() takes at most 1 argument (2 given)

                        --
                        Neil Cerutti

                        Comment

                        • Georg Brandl

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

                          Neil Cerutti wrote:
                          On 2006-09-29, Steve Holden <steve@holdenwe b.comwrote:
                          >MonkeeSage wrote:
                          >>So far as unobfuscated versions go, how about the simple:
                          >>>
                          >>def to_bin(x):
                          >> out = []
                          >> while x 0:
                          >> out.insert(0, str(x % 2))
                          >> x = x / 2
                          >> return ''.join(out)
                          >>>
                          >>Regards,
                          >
                          It was surprising that
                          >
                          >>>i = int("111010101" , 2)
                          >
                          is a one-way operation.
                          >
                          >>>s = str(i, 2)
                          Traceback (most recent call last):
                          File "<stdin>", line 1, in ?
                          TypeError: str() takes at most 1 argument (2 given)
                          str() is not only for converting integers, but all other types too.
                          An explicit argument for this special case is not Pythonic IMO.

                          Georg

                          Comment

                          • Neil Cerutti

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

                            On 2006-09-29, Georg Brandl <g.brandl-nospam@gmx.netw rote:
                            Neil Cerutti wrote:
                            >On 2006-09-29, Steve Holden <steve@holdenwe b.comwrote:
                            >>MonkeeSage wrote:
                            >>>So far as unobfuscated versions go, how about the simple:
                            >>>>
                            >>>def to_bin(x):
                            >>> out = []
                            >>> while x 0:
                            >>> out.insert(0, str(x % 2))
                            >>> x = x / 2
                            >>> return ''.join(out)
                            >>>>
                            >>>Regards,
                            >>
                            >It was surprising that
                            >>
                            >>>>i = int("111010101" , 2)
                            >>
                            >is a one-way operation.
                            >>
                            >>>>s = str(i, 2)
                            >Traceback (most recent call last):
                            > File "<stdin>", line 1, in ?
                            >TypeError: str() takes at most 1 argument (2 given)
                            >
                            str() is not only for converting integers, but all other types
                            too. An explicit argument for this special case is not Pythonic
                            IMO.
                            I suppose two wrongs wouldn't make a right. ;)

                            --
                            Neil Cerutti

                            Comment

                            Working...