Tuesday, December 07, 2004

Fastest way to convert numbers

Ever wanted to convert thousands of numbers from one base to another!!! Well M$ Windoze's 'calc' is just MORE THAN useless, unless, of course, you are ready to copy-paste each of those thousands of numbers, convert it and then again copy-paste it back to some other file! BTW, even if you are ready to do so, your boss probably will be LEAST impressed by that ;-)

Yes, you are right! Linux (*nix) is the ONLY answer! No need of perl! Neither any arcane scripting. Just plain 'bc' is enough.
Here's the trick:
  1. Copy all your numbers in plain text file.
  2. Put 'ibase=16' as your first and 'quit' as last lines in the file.
  3. You can put 'obase=n' as your second line, in case your output should be in base 'n' (10 is default, so skip it).
  4. bc your_file
BINGO! There you are! All those thousands of numbers are converted to required base in a jiffy!
Note: You need to redirect output of 'step 4' and collect it in a seperate file.

You can use any combination of ibase (Input base) and obase (Output base) in the range '2 thro 16'. But you need to ensure that all input numbers are in CAPITALS! Not a problem at all, use this command to achieve that:
# cat your_file | tr a-f A-F > another_file
(of course, the better way is open in vim and, ggVGgU)
Sample run:
# cat /tmp/hex.txt
ibase=16
FF
100
AF
quit

# bc /tmp/hex.txt
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
255
256
175
I'm not arguing that this solution is better than Perl-based or C-based or Script-based ones. But this definitely is the least effort solution given the fact that 'bc' is a part of any standard Linux installation.

No comments: