view raw
sebastian nielsen sebastian nielsen - 6 months ago 53
Perl Question

Perl: Convert string to number (NOT literally!)

I want to convert a string to number. You might read this as I want to convert "5" into 5, but no.

The conversion should be like this:

"aa" -> 24929
"55" -> 13621
"sebastian" -> 2128681077170648998254
"SEBASTIAN" -> 1536070381281124893006
\xFF\xFF -> 65536

Ergo, treat the input character string as a base^256 number, and convert it accordingly.

In the same way, I want also to be able to convert numbers back into their char representation.

How can I accomplish this in perl?

my $n = unpack("Q>", substr(("\0"x8) . $s, -8));

However, that won't handle the numbers for sebastian and SEBASTIAN since they are too large for Perl's native types (64 bits, so 8 bytes). You'd need an library that provides more precision (such as Math::Int128) or one that provides an arbitrary amount of precision (such as Math::BigInt).

Fastest, but limited to 128 bits (16 bytes):

use Math::Int128 qw( net_to_uint128 );

my $n = net_to_uint128(substr(("\0"x8) . $s, -8));


use Math::Int128 qw( hex_to_uint128 );

my $n = hex_to_uint128(unpack('H*', $s));

Require best performance from Math::BigInt:

use Math::BigInt only => 'GMP';

my $n = Math::BigInt->from_hex(unpack('H*', $s));

Falls back to slower code if GMP is not available:

use Math::BigInt try => 'GMP';

my $n = Math::BigInt->from_hex(unpack('H*', $s));