Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Created November 13, 2024 11:18
Show Gist options
  • Save x-yuri/c25a905a1934e35af05e29e34cf8fd55 to your computer and use it in GitHub Desktop.
Save x-yuri/c25a905a1934e35af05e29e34cf8fd55 to your computer and use it in GitHub Desktop.
perl: internal representation of numbers

perl: internal representation of numbers

Perl can internally represent numbers in 3 different ways: as native integers, as native floating point numbers, and as decimal strings.

https://perldoc.perl.org/perlnumber

Small integer numbers are stored as signed integers. When that is not possible perl switches to unsigned integers. And then to floating point numbers:

a.pl:

use strict;
use warnings;
use B qw(svref_2object SVf_IVisUV SVf_NOK);

sub ntype {
    my $i = shift;
    my $sv = svref_2object(\$i);
      $sv->FLAGS & SVf_NOK    ? "NV"  # float
    : $sv->FLAGS & SVf_IVisUV ? "UV"  # unsigned int
    :                           "IV"; # signed int
}

# print ntype(0x7fff_ffff_ffff_ffff), "\n";      # IV
print ntype(1 << 63 - 1), "\n";                # IV

# print ntype(0x8000_0000_0000_0000), "\n";      # UV
print ntype(1 << 63), "\n";                    # UV

# print ntype(0xffff_ffff_ffff_ffff), "\n";      # UV
print ntype(~0), "\n";                         # UV

# print ntype(0xffff_ffff_ffff_ffff + 1), "\n";  # NV
print ntype(~0 + 1), "\n";                     # NV

https://stackoverflow.com/questions/25081972/maximum-integer-in-perl/25083776#25083776

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment