Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: integer container for float

by syphilis (Archbishop)
on Mar 28, 2016 at 12:44 UTC ( [id://1158955]=note: print w/replies, xml ) Need Help??


in reply to integer container for float

BrowserUk has nicely covered the case where $Config{ivsize} == 8.

Similarly it's possible to pack/unpack single precision floats when $Config{ivsize} == 4.
Obviously, you can't use the "Q" template because, according to the docs, that applies only to ivsize of 8. But you can use the "j" (or "J") templates with the "f" template:
#!perl -l use strict; use warnings; use Config; my $val = 3.625; if($Config{ivsize} == 4) { my $to_int = unpack 'j', pack 'f', $val;; print $to_int; # 1080557568 my $to_float = unpack 'f', pack 'j', $to_int;; print $to_float; # 3.625 } else { print "Can't pack C floats to IV/UV"; }
Cheers,
Rob

Replies are listed 'Best First'.
Re^2: integer container for float
by BrowserUk (Patriarch) on Mar 28, 2016 at 14:08 UTC

    Indeed.

    He could even use 2 x 32-bit ints as an intermediary for a double:

    ($lo, $hi) = unpack 'NN', pack 'd', 3.14159265358979;; print $lo, $hi;; 288179284 4213246272 print unpack 'd', pack 'NN', 288179284, 4213246272;; 3.14159265358979

    Or even 4 x 16-bit ints:

    ( $_0, $_1, $_2, $_3 ) = unpack 'n*', pack 'd', exp(1);; print unpack 'd', pack 'n*', $_0, $_1, $_2, $_3;; 2.71828182845905

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1158955]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-20 01:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found