convert floats to their 4 byte representation

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

    #1

    convert floats to their 4 byte representation

    I need to take floats and dump out their 4 byte hex representation.
    This is easy with ints with the built in hex function or even better
    for my purpose

    def hex( number, size ):
    s = "%"+str(siz e) + "X"
    return (s % number).replace (' ', '0')

    but I haven't been able to find anything for floats. Any help would be
    great.

  • Alex Martelli

    #2
    Re: convert floats to their 4 byte representation

    godavemon <davefowler@gma il.com> wrote:
    [color=blue]
    > I need to take floats and dump out their 4 byte hex representation.
    > This is easy with ints with the built in hex function or even better
    > for my purpose
    >
    > def hex( number, size ):
    > s = "%"+str(siz e) + "X"
    > return (s % number).replace (' ', '0')
    >
    > but I haven't been able to find anything for floats. Any help would be
    > great.[/color]

    floats' internal representation in Python is 8 bytes (equivalent to a C
    "double"). However, you can import struct and use struct.pack('f' ,x) to
    get a 4-byte ("single precision") approximation of x's 8-byte value,
    returned as a string of 4 bytes; you may force little-endian by using as
    the format '<f' or big-endian by using '>f'; then loop on each character
    of the string and get its ord(c) [a number from 0 to 255] to format as
    you wish.

    For example

    import struct
    def float_hex4(f):
    return ''.join(('%2.2x '%ord(c)) for c in struct.pack('f' , f))

    or variants thereof.


    Alex

    Comment

    • Tim Chase

      #3
      Re: convert floats to their 4 byte representation

      > s = "%"+str(siz e) + "X"[color=blue]
      > return (s % number).replace (' ', '0')[/color]

      While I don't have a fast and easy way to represent floats, you
      may want to tweak this to be

      return ("%0*X" % (size,number))

      which will zero-pad the number in hex to "size" number of places
      in a single step. It also helps prevent problems where there might
      [color=blue]
      > but I haven't been able to find anything for floats. Any help
      > would be great.[/color]

      My first stab at such an attempt:
      [color=blue][color=green][color=darkred]
      >>> from struct import pack, unpack
      >>> s = pack("d", 3.14)
      >>> i = unpack("q", s)
      >>> "%X"%i[/color][/color][/color]
      '40091EB851EB85 1F'[color=blue][color=green][color=darkred]
      >>> def floatAsHex(f, size):[/color][/color][/color]
      .... return "%0*X" % (size, unpack("q", pack("d", f))[0])
      ....[color=blue][color=green][color=darkred]
      >>> floatAsHex(3.14 , 20)[/color][/color][/color]
      '000040091EB851 EB851F'

      It's ugly, it's hackish, it's likely architecture-dependant, but
      it seems to do what you're describing.

      -tkc




      Comment

      • Grant Edwards

        #4
        Re: convert floats to their 4 byte representation

        On 2006-06-14, godavemon <davefowler@gma il.com> wrote:
        [color=blue]
        > I need to take floats and dump out their 4 byte hex representation.[/color]

        struct

        --
        Grant Edwards grante Yow! Darling, my ELBOW
        at is FLYING over FRANKFURT,
        visi.com Germany...

        Comment

        • Scott David Daniels

          #5
          Re: convert floats to their 4 byte representation

          godavemon wrote:[color=blue]
          > I need to take floats and dump out their 4 byte hex representation.
          > This is easy with ints with the built in hex function or even better
          > for my purpose
          >
          > def hex( number, size ):
          > s = "%"+str(siz e) + "X"
          > return (s % number).replace (' ', '0')[/color]

          This should be a trifle nicer:
          def hexx(number, size): # don't shadow the "hex" builtin
          s = "%0s" + str(size) + "X"
          return s % number
          [color=blue]
          > but I haven't been able to find anything for floats. Any help would be
          > great.[/color]

          Getting to float bytes is tougher.
          First, python Floats are C Doubles, so you probably mean 8=byte hex.

          import array

          def eights(number, swap=False):
          data = array.array('d' , [number])
          if swap:
          data.byteswap()
          return ' '.join(hexx(ord (char), 2) for char in data.tostring() )

          def fours(number, swap=False):
          data = array.array('f' , [number])
          if swap:
          data.byteswap()
          return ' '.join(hexx(ord (char), 2) for char in data.tostring() )

          --Scott David Daniels
          scott.daniels@a cm.org

          Comment

          • godavemon

            #6
            Re: convert floats to their 4 byte representation

            I've been a member for a while but I had no idea how helpful this form
            is. I had a one hour meeting and when I came back there were 4
            replies. Thanks for your help!


            Scott David Daniels wrote:[color=blue]
            > godavemon wrote:[color=green]
            > > I need to take floats and dump out their 4 byte hex representation.
            > > This is easy with ints with the built in hex function or even better
            > > for my purpose
            > >
            > > def hex( number, size ):
            > > s = "%"+str(siz e) + "X"
            > > return (s % number).replace (' ', '0')[/color]
            >
            > This should be a trifle nicer:
            > def hexx(number, size): # don't shadow the "hex" builtin
            > s = "%0s" + str(size) + "X"
            > return s % number
            >[color=green]
            > > but I haven't been able to find anything for floats. Any help would be
            > > great.[/color]
            >
            > Getting to float bytes is tougher.
            > First, python Floats are C Doubles, so you probably mean 8=byte hex.
            >
            > import array
            >
            > def eights(number, swap=False):
            > data = array.array('d' , [number])
            > if swap:
            > data.byteswap()
            > return ' '.join(hexx(ord (char), 2) for char in data.tostring() )
            >
            > def fours(number, swap=False):
            > data = array.array('f' , [number])
            > if swap:
            > data.byteswap()
            > return ' '.join(hexx(ord (char), 2) for char in data.tostring() )
            >
            > --Scott David Daniels
            > scott.daniels@a cm.org[/color]

            Comment

            • Cameron Laird

              #7
              Re: convert floats to their 4 byte representation

              In article <1150301012.403 651.198440@g10g 2000cwb.googleg roups.com>,
              godavemon <davefowler@gma il.com> wrote:[color=blue]
              >I've been a member for a while but I had no idea how helpful this form
              >is. I had a one hour meeting and when I came back there were 4
              >replies. Thanks for your help!
              >
              >
              >Scott David Daniels wrote:[color=green]
              >> godavemon wrote:[color=darkred]
              >> > I need to take floats and dump out their 4 byte hex representation.[/color][/color][/color]

              Comment

              Working...