thatmguy has asked for the wisdom of the Perl Monks concerning the following question:

Greetings!
I am receiving two values that look like two short integers but which in reality are two 16-bit halves of a 32-bit IEEE float. I'm looking for a way to concatenate the two 16-bit halves and then be able to work with the result as a float. Example:
my $var1 = 17232; # really 0100001101010000 my $var2 = 12822; # really 0011001000010110 my $var3 = $var1 << 16 | $var2; # 01000011010100000011001000010110
I am looking for a way to convert or otherwise have $var3 recognized as 208.19565 and not an integer like 1129329174. Anyone have an idea? Thanks!

Replies are listed 'Best First'.
Re: 32bit float from two halves
by Anonymous Monk on Aug 10, 2016 at 00:00 UTC

    Read the docs on pack/unpack.

    $ perl -we 'print unpack "f", pack "vv", reverse 17232, 12822;'
    208.195648193359
    

      Worked perfectly - thank you!
Re: 32bit float from two halves
by hexcoder (Curate) on Aug 10, 2016 at 21:16 UTC
    ... my $var3 = unpack 'f', pack 'V', $var1 << 16 | $var2;
    and you get your float in $var3.
      Makes sense - reverse and pack two shorts, then unpack as float vs build a long, reverse/pack it as a long, then unpack as float. Thanks for both solutions, it's pretty cool to see the proverbial cat skinned multiple ways...

        Just to make sure the right idea gets across — the reverse as seen here merely changes argument order and is otherwise irrelevant. (It's quicker to type in "reverse" than to swap those numbers in a command line.)