Skip to content

Instantly share code, notes, and snippets.

@stephenmm
Created July 10, 2013 19:25
Show Gist options
  • Save stephenmm/5969376 to your computer and use it in GitHub Desktop.
Save stephenmm/5969376 to your computer and use it in GitHub Desktop.
Simple script to convert numbers to binary hex or decimal. Can be used directly or used as a module for other scripts.
#!/usr/bin/perl -w
# AUTHOR: Stephen Meckley 7/10/2013
package cnvrt;
use strict;
use warnings;
__PACKAGE__->main(@ARGV) unless caller;
sub main {
my $class = shift;
my $obj = $class->new(@ARGV);
if( $#ARGV < 0 || $#ARGV > 1 ){ $obj->help(); exit 1; }
if( $ARGV[0] eq "--help" ){ $obj->help(); exit 1; };
if( $ARGV[0] eq "--test_self" ){ $obj->test_self() };
print $obj->convert( $ARGV[0], $ARGV[1] )."\n";
}
sub new { my $class = shift; return bless [@_], $class; }
sub help {
my $self = shift;
print "usage: cnvrt <format> <number> \n";
print " eg: cnvrt 016b_ 0x840A yields: 1000_0100_0000_1010\n";
print " eg: cnvrt 08x_ 0b1_0010_1000_1101 yields: 0000_128d \n";
print " eg: cnvrt 09d, 128d yields: 000,004,749 \n";
print " eg: cnvrt d, 0x0000_128d yields: 4,749 \n";
print " eg: cnvrt 016b_ 4,749 yields: 1001_01000_1101 \n";
}
sub convert {
my $self = shift;
my( $frmt, $val ) = @_;
$val =~ s/[_,]//g;
if( $val =~ /^(\d+)$/ ){ # All digits with no prefix assumes decimal
} elsif( $val =~ /^[0']b([10]+)/i ){ # look for binary numbers first
$val = "0b$1";
} elsif( $val =~ /^('h|0x)([\da-f]+)/i ){ # Then look for hex
$val = "0x$2";
} elsif( $val =~ /^([\da-f]+)$/i ) { # Finally if it looks hex do hex
$val = "0x$1";
} else {
help(); die "ERROR: no valid number provided. Read help above for examples.";
}
$val = eval( $val );
my $format = 'd';
my $seporator = '';
$format = $1 if( $frmt =~ /^(\d*[bdx])/ ) ;
$seporator = $1 if( $frmt =~ /^\d*[bdx]([,_])/ ) ;
my $out = eval( "sprintf (\"%$format\n\", $val )" );
$out=reverse($out);
if( $seporator eq '_' ){
$out =~ s/(....)(?=.)/${1}_/g;
}
if( $seporator eq ',' ){
$out =~ s/(...)(?=.)/${1},/g;
}
$out=reverse($out);
chomp($out);
return $out;
}
sub test_self {
my $self = shift;
require "Test/More.pm";
Test::More->import('no_plan');
like(1,qr/1/ ,"TEST_0");
like($self->convert('016b_', '0x128d'), qr/0001_0010_1000_1101/ ,"TEST_1 works");
like($self->convert('08x_', '0b1_0010_1000_1101'), qr/0000_128d/ ,"TEST_2 works");
like($self->convert('09d,', '0000_0000_0000_128d'), qr/000,004,749/ ,"TEST_3 works");
like($self->convert('d,', '0000_0000_0000_128d'), qr/4,749/ ,"TEST_4 works");
like($self->convert('016b_', '4,749'), qr/1_0010_1000_1101/ ,"TEST_5 works");
exit;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment