Base conversions with bc

Whiile reading through Planet Sun I stumbled across Chris Gerhard’s base conversion post. I replied with an alternate solution using bc(1), which I have used extensively through the years. bc(1) is a command line calculator that can convert between bases when the “ibase” and “obase” options are used. The following example shows how to convert a base 10 number to it’s hexidecimal equivalent:

$ bc
obase=16
12345677
BC614D

We can also use bc to convert a hexidecimal value to decimal:

$ bc
ibase=16
FF
255

This gets even better! We can convert a hexidecimal value to binary:

$ bc
ibase=16
obase=2
FF
11111111

I really really like bc (and dc)!

Command line dictionary

The UNIX tips mailing list provides daily UNIX hints and tricks:

http://www.ugu.com/sui/ugu/show?tip.today

I received a tip a few months back that showed how to use lynx to lookup a word on dictionary.com, and decided to add this to my .profile:

dict () {
if [ “${1}” != “” ]
then
lynx -cfg=/dev/null -dump “http://www.dictionary.com/cgi-bin/dict.pl?term=$1”
| more
else
echo “USAGE: dict word”
fi
}

This function accepts an argument, and passes the URL with the word to lookup to lynx. The function can be invoked by typing “dict” at a shell prompt:

$ dict manager

The one who ruins my life with their clueless ways

I had to throw that in :) Here is a real run:

$ dict orthogonal

[1]Dictionary.com _________________________ Search
(_) Dictionary (_) Thesaurus (_) Web
[2]Home Premium: [3]Sign up | [4]Login

or?thog?o?nal [5] Audio pronunciation of “orthogonal”
( P ) [6]Pronunciation Key (?r-th g -n l)
adj.
1. Relating to or composed of right angles.
2. Mathematics.
a. Of or relating to a matrix whose transpose equals its
inverse.
b. Of or relating to a linear transformation that preserves the
length of vectors.

[ … ]

As you can see, this is rather useful (especially when you use vi to draft all of your documents).

Bash arrays

I have been trying to get a better grasp of some advanced bash concepts, and have been reading through the following reference manual:

http://www.tldp.org/LDP/abs/html/

I am pretty familiar with C and perl arrays, but have never had a need to use arrays in a bash script. The syntax for a bash array is almost identical to Perl:

array[1]=12
echo ${array[1]}

This assigns the value 12 to the first slot in the array. Since bash variables are untyped, we can assign a string to the same array:

array[2]=”my string”
echo ${array[2]}

This assigns the string “my string” to slot two in the array. Useful stuff!