Friday, June 5, 2009

A better unit conversion script (h2b b2h h2d d2h)

So I have been trying to get a robust unit conversion script for a while and I have had a few different solutions but I always had some troubles with them. bc is the calculator tool that comes with most linux distributions and is pretty widely available and is very good at doing the conversions but it too had some difficulties if the string containing the numbers was not formatted just right. So I use a small Perl wrapper script to do the formatting and then pass it on to bc. This seems to be working very well for me now. You can see the code below.

I also have some vim commands that call this script and allow me to do do conversions right from within vim (will add this vim code later). I also have some csh alias commands that I will add later as well.

It has proven to be very powerful and has improved my coding and debugging efficiency. Hope someone else finds it useful.

##### FILE: ######

#!/usr/local/bin/perl -w
# Use the bc function to do conversions..
## | check if called properly
#if ($#ARGV >= 0) {
if ($#ARGV < 2) {
print " Usage: $0 \n" ;
print " used to wrap bc so you can set the base input and output \n" ;
print " in order to do conversions. For example to convert binary \n" ;
print " to hex, run the following command: \n" ;
print " 2 16 1001_1011 \n" ;
print " RESULT: 9B \n" ;

$ARGV[2] =~ s/_//g;
$ARGV[2] =~ tr/a-z/A-Z/;

# The following is a csh command that tells the tool bc the output base type,
# the input base type and the expression to run.
my $cmd = "bc << EOF \
obase=$ARGV[1]; \
ibase=$ARGV[0]; \
$ARGV[2]; \
quit; \

#print " $cmd \n";
#system("$cmd") == 0 or die "system $cmd failed: $?";
my $result = `$cmd`;
# Make the result easier to read by inserting underscores
if ( ( $ARGV[1] eq "2" ) || ( $ARGV[1] eq "16" ) ) {
$result = reverse $result;
$result =~ s/(\w{4})/$1_/g;
$result = reverse $result;
$result =~ s/^_//g;
print "$result";

No comments:

Post a Comment