Professional Web Applications Themes

hex to float conversion - Ruby

I have a hex number that I need to convert to a 32 bit float eg 0x44361000 => 728.25 (from http://sandbox.mc.edu/~bennet/cs110/flt/ftod.html) Ive written some ugly code to do it, but Im sure there must be a nicer way with pack/unpack/sprintf I also need to go from floats to Hex too Can any one help?...

  1. #1

    Default hex to float conversion

    I have a hex number that I need to convert to a 32 bit float

    eg 0x44361000 => 728.25 (from
    http://sandbox.mc.edu/~bennet/cs110/flt/ftod.html)

    Ive written some ugly code to do it, but Im sure there must be a nicer
    way with pack/unpack/sprintf

    I also need to go from floats to Hex too

    Can any one help?
    Paul Guest

  2. #2

    Default Re: hex to float conversion

    ca (Paul) writes:
     
     
     

    If you have the original hex in a string, you'll need to convert it to
    an int first. Then you have to put it in an array, call pack on the array,
    and call unpack on the resulting string. What you get out of that is
    again an array so you need to extract the element you want. The
    whole thing looks like this:

    irb(main):001:0> s='0x44361000'
    => "0x44361000"
    irb(main):002:0> f=[s.to_i(16)].pack('L').unpack('F')[0]
    => 728.25

    Going the other way is similar:

    irb(main):003:0> sprintf("0x%08x", [f].pack('F').unpack('L')[0])
    => "0x44361000"

    -Mark
    Mark Guest

  3. #3

    Default Re: hex to float conversion


    On Feb 25, 2004, at 9:09, Paul wrote:
     

    I'm not sure about the various sign-bit issues, but something like:

    hex = 0x44361000
    p [ hex ].pack("I").unpack("f")[0]

    Might get you started.


    Cheers

    Dave



    Dave Guest

Similar Threads

  1. #25562 [Opn->Bgs]: Float to String to Float conversion error
    By helly@php.net in forum PHP Development
    Replies: 0
    Last Post: September 16th, 08:02 PM
  2. #25562 [NEW]: Float to String to Float conversion error
    By daseymour at 3hc dot org in forum PHP Development
    Replies: 0
    Last Post: September 16th, 07:36 PM
  3. preventing string conversion to float.
    By Little Bill in forum PERL Miscellaneous
    Replies: 1
    Last Post: July 20th, 02:27 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139