Your skill will accomplishwhat the force of many cannot PerlMonks

### Re^3: Detecting whether UV fits into an NV

by ikegami (Pope)
 on Feb 27, 2020 at 07:29 UTC Need Help??

in reply to Re^2: Detecting whether UV fits into an NV
in thread Detecting whether UV fits into an NV

```my \$x = ( 1 << 54 ) | 1;
say \$x;  # 18014398509481985

\$x = unpack 'F', pack 'F', \$x;
\$x = unpack 'J', pack 'J', \$x;

say \$x;  # 18014398509481984

To support negative numbers, use I instead of J for negative numbers.

The following is a little bit truer to a cast, but it's far more complicated, far more fragile (can fail for overloaded and magical vars), and technically uses XS:

```use strict;
use warnings;
use feature qw( say );

use B qw( svref_2object );

my \$x = ( 1 << 54 ) | 1;
say \$x;  # 18014398509481985

# Add the value as an NV to the scalar.
{ no warnings qw( void ); log \$x; }

# Make it so the scalar contains just an NV.
\$x = svref_2object(\\$x)->NV;

# Add the value as an IV or UV to the scalar.
{ no warnings qw( void ); \$x | 1; }

# Make it so the scalar contains just an IV or UV.
\$x = svref_2object(\\$x)->int_value;

say \$x;  # 18014398509481984

Replies are listed 'Best First'.
Re^4: Detecting whether UV fits into an NV
by syphilis (Bishop) on Feb 27, 2020 at 10:42 UTC
Cool - and thanks for going to the trouble of providing that. (I can spend hours trying to get pack and unpack to do what I want them to do ;-)
Both of your approaches still fail to deal correctly with certain values when older Microsoft compilers are used.
All is good for the value of 18014398509481985, irrespective of compiler. The value of \$x changes from 18014398509481985 to 18014398509481984, indicating correctly that 18014398509481985 is not representable as a double.

However, IIUC, the value of \$x should not alter if \$x is initialized to (eg) 18446744073709549568 or 18446744073709139968 as both values are representable as a double.
But those values do change with those older Microsoft compilers - again, I believe, indicative of that same problem (that I keep hitting) that afflicted Microsoft compilers until some point after Visual Studio 2010 and no later than Visual Studio 2017.

At this point, the only thing that's working on these troublesome Microsoft compilers are the subs I provided in my initial post.

I should point out that I haven't yet got to assessing jcb's contribution. I'll try to get to it over the weekend, or whenever I can find the time.

Cheers,
Rob

Create A New User
Node Status?
node history
Node Type: note [id://11113475]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2020-12-04 20:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How often do you use taint mode?

Results (62 votes). Check out past polls.

Notices?