Once upon a time, I was working with filenames in a caching system and ran into this problem: In our database, all images were saved with the filenames created as long integers. In the caching system, these same filenames were displayed as hex values. How would you go about taking a long list of files from the DB to process in the caching system? The Unix Basic Calaculator, of course!

bc is described as "an arbitrary precision calculator language". Despite what you might think, it's not scary, and it's incredibly handy! The syntax is much like using C, but you don't even need to know most of that in order to work with it for basic tasks.

In this particular scenario, we are just going to pipe our values into bc, and let it know to change the base of the output to hex. By default, the input base (ibase) and the output base (obase) are both decimal (base 10). We just need to set this to hexadecimal (base 16).

obase=16

It's really that simple! Now let's see it in an example. We are going to put 5 values into a file that are stored in decimal.

echo -e "45 107 37 143 88" > mylist

Now, we simply pipe the obase and the list as one stream into bc, and we should receive our values. (Don't forget the paranthesis here; we want to pipe all of the input as a whole).

( echo "obase=16" ; cat mylist ) | bc 2D 6B 25 8F 58

Tada! Easy, isn't it? If the input were in something other than decimal, you could easily change the ibase in the same manner so bc would know how to process it.

When dealing with my particular caching system, it required all of the filesnames to be in lowercase, however. So here's a quick one-liner to change these to lowercase.

( echo "obase=16" ; cat mylist ) | bc | tr "A-Z" "a-z" 2d 6b 25 8f 58