Browse files

The goodie to convert a given hex value to its equivalent ASCII repre…

…sentation
  • Loading branch information...
1 parent e88db42 commit 8faf48358cfdd5a59dc3749b1d18e4ff05bc8dc6 @koosha-- koosha-- committed Dec 2, 2012
Showing with 67 additions and 0 deletions.
  1. +48 −0 lib/DDG/Goodie/HexToASCII.pm
  2. +19 −0 t/HexToASCII.t
View
48 lib/DDG/Goodie/HexToASCII.pm
@@ -0,0 +1,48 @@
+package DDG::Goodie::HexToASCII;
+# ABSTRACT: Returns the ASCII representaion of a given hexadecimal value. (If printbale of course).
+
+use strict;
+
+use DDG::Goodie;
+# Used to restrict long generated outputs
+use constant MAX_OUTPUT_LEN => 256;
+
+triggers start => 'ascii';
+
+zci is_cached => 1;
+zci answer_type => 'ascii';
+
+primary_example_queries 'ascii 0x74657374';
+secondary_example_queries 'ascii 0x5468697320697320612074657374';
+description 'Return the ASCII representation of a given printable HEX number.';
+name 'HexToASCII';
+code_url 'http://github.com';
+category 'computing_tools';
+topics 'programming';
+attribution github => ['https://github.com/koosha--', 'koosha--'],
+ twitter => '_koosha_';
+
+handle remainder => sub {
+ my $value = $_;
+ $value =~ s/^\s+//;
+ $value =~ s/\s+$//;
+ if ($value =~ /^(?:[0\\]x)?([0-9a-f]+)$/i or
+ $value =~ /^([0-9a-f]+)h?$/i) {
+ my @digits = $1 =~ /(..)/g;
+ my $string = '';
+ foreach my $digit (@digits) {
+ my $hex = hex $digit;
+ return if $hex <= 0x1F || $hex >= 0x7F;
+ $string .= chr $hex;
+ }
+ $string =~ s/\n/ /g;
+ # Don't let long strings make the output untidy
+ if (length($string) > MAX_OUTPUT_LEN) {
+ $string = substr($string, 0, MAX_OUTPUT_LEN - 3) . '...';
+ }
+ return "ASCII: $string";
+ }
+ return;
+};
+
+1;
View
19 t/HexToASCII.t
@@ -0,0 +1,19 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use Test::More;
+use DDG::Test::Goodie;
+
+zci answer_type => 'ascii';
+zci is_cached => 1;
+
+ddg_goodie_test(
+ [qw(
+ DDG::Goodie::HexToASCII
+ )],
+ 'ascii 0x74657374' => test_zci('ASCII: test'),
+ 'ascii 0x5468697320697320612074657374' => test_zci('ASCII: This is a test'),
+);
+
+done_testing;

0 comments on commit 8faf483

Please sign in to comment.