Hello Monks,

The business values I operated are floats; meanwhile the module I use to them in shared memory uses integers, that also guarantees the atomicity of writing int-values in shared memory.

Is there any way to pack (not convert) float to integer, without loosing precision? Way# 1

my $packed_integer = int($float * 1_000_000); my $unpacked_float = $packed_integer / 1_000_000;

Obviously, I loose precision here. In C I can do to manipulation with pointers, to get the result I like:

assert(sizeof(int) >= sizeof(float)); float f = ...; int *i_ptr = (int*)&f; int i = *int;

Then I've found can do something like that via pack/upack build-ins in Perl:

my $v = 1/3; my $v2 = unpack("F", pack("j", unpack("j", pack("F", $v)))); print ("v = $v\nv = $v2\n"); # v = 0.333333333333333 # v = 0.333333333333333

Seems fine.

Thanks!

WBR, basiliscos.

In reply to integer container for float by basiliscos

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.