Link to home
Start Free TrialLog in
Avatar of guadalupe
guadalupe

asked on

Module to convert any multiple of bytes to any other multiple?

Is there a module that can handle conversion from any multiple of byte to any other multiple?  For example

$GB = &convert(kB,GB,$num);

This sub would take the first arg as what $num IS (a # of kB) and transform to GB.

$kB = &convert(GB,kB,$num);

This would take $num understood to be in GB and convert to kB...

The idea is faily simple but the multiples get annoying to have to account for all cases...?
Avatar of guadalupe
guadalupe

ASKER

Well I though about and came up with this code:

sub convert_k($$$)
{
      ($from,$to,$number) = @_;

      #Set up hash for math conversions between bytes - kB and MB GB
      $byteMath{"B"} = 1;

      $byteMath{"kB"} = 2;

      $byteMath{"MB"} = 3;

      $byteMath{"GB"} = 4;

      $byte_multiple = 1024;

      $power = $byteMath{$from} - $byteMath{$to};

      return $number * ($byte_multiple ** $power);
}

I had hoped to not have to right the code as no idea came to mind and then it hit me.  I would still be interested to know if a modual exists.  But the code above is good so take it if it interests you!
A stupid but good improvment:


#!/usr/local/bin/perl


print &convert_k($ARGV[0],$ARGV[1],$ARGV[2]);


sub convert_k($$$)
{
      ($from,$to,$number) = @_;

      $from      = uc($from);

      $to      = uc($to);

      #Set up hash for math conversions between bytes - kB and MB GB
      $byteMath{"B"} = 1;

      $byteMath{"KB"} = 2;

      $byteMath{"MB"} = 3;

      $byteMath{"GB"} = 4;

      $byte_multiple = 1024;

      $power = $byteMath{$from} - $byteMath{$to};

      return $number * ($byte_multiple ** $power);
}
ASKER CERTIFIED SOLUTION
Avatar of monas
monas
Flag of Lithuania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you!  Very nice though I'm still curious if one already exists  just to see how "they" chose to do it...