2012-03-07 13:24:10 -08:00
|
|
|
package DDG::Goodie::Base;
|
2014-08-20 11:45:33 -07:00
|
|
|
# ABSTRACT: convert numbers between arbitrary bases
|
2012-05-23 19:05:08 -07:00
|
|
|
|
2015-02-22 12:09:29 -08:00
|
|
|
use strict;
|
2012-03-07 13:24:10 -08:00
|
|
|
use DDG::Goodie;
|
2014-08-20 11:45:33 -07:00
|
|
|
|
2012-05-23 19:05:08 -07:00
|
|
|
use Math::Int2Base qw/int2base/;
|
|
|
|
use 5.010;
|
2014-08-14 16:32:12 -07:00
|
|
|
use bigint;
|
2012-03-07 13:24:10 -08:00
|
|
|
|
2012-03-12 08:57:25 -07:00
|
|
|
my %base_map = (
|
|
|
|
hex => 16,
|
|
|
|
hexadecimal => 16,
|
|
|
|
oct => 8,
|
|
|
|
octal => 8,
|
|
|
|
binary => 2,
|
|
|
|
);
|
2014-10-15 00:17:44 -07:00
|
|
|
my $map_keys = join '|', keys %base_map;
|
2012-05-23 19:05:08 -07:00
|
|
|
|
2012-04-15 18:31:26 -07:00
|
|
|
triggers any => 'base', keys %base_map;
|
2012-03-12 08:57:25 -07:00
|
|
|
|
2012-05-23 19:05:08 -07:00
|
|
|
zci answer_type => "conversion";
|
|
|
|
zci is_cached => 1;
|
|
|
|
|
2012-03-07 13:24:10 -08:00
|
|
|
handle query_clean => sub {
|
2014-10-15 00:17:44 -07:00
|
|
|
return unless /^(?<num>[0-9]+)\s*(?:(?:in|as|to)\s+)?(?:(?<bt>$map_keys)|(?:base\s*(?<bn>[0-9]+)))$/;
|
|
|
|
my $number = $+{'num'};
|
|
|
|
my $base = $+{'bn'} // $base_map{$+{bt}};
|
2012-03-07 13:24:10 -08:00
|
|
|
return if $base < 2 || $base > 36;
|
|
|
|
my $based = int2base($number, $base);
|
2014-10-15 00:17:44 -07:00
|
|
|
return "$number in base $base is $based",
|
|
|
|
structured_answer => {
|
|
|
|
input => ["$number"],
|
2015-01-08 23:52:22 -08:00
|
|
|
operation => 'Decimal to base ' . $base,
|
2014-10-15 00:17:44 -07:00
|
|
|
result => $based
|
|
|
|
};
|
2012-03-07 13:24:10 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
1;
|