Tuesday, May 17, 2011

bc - Unix calculator



  Whenever we need to do some calculation, we open the calculator in the windows. For unix programmers, why to go for windows calculator when we have an in-built one, bc.  bc is a unix command which stands for bench calcultor. Depending on the way we use it, it can either look like a programming language or as a interactive mathematic shell. Let us see in this article how to use bc  to do some simple arithmetic.

   bc can be invoked either as a pipe of other command OR by getting into the interactive mode. Let us start by seeing it from the command line perspective.


1. To do a simple addition of 2 numbers:
$ echo 4+5 | bc
9
  We can also give the numbers in the form of variables as well:
$ x=20
$ y=10

$ echo $x+$y | bc
30
  In the same way, we can get the subtraction(-) and the modulus(%) operations done as well.

2. To do a multiplication of 2 numbers;
$ echo $x\*$y | bc
200
   Note that we had to put a backslash to escape the * without which the * would have got treated as a wild card leading to unexpected behavior.

3. To divide 2 numbers using bc, we use the / operator:
$ x=12; y=7
$ echo $x/$y | bc
1
  Note that the result does not contain the fractional part. bc does not give the fraction of the division by default. This can be obtained using one of the special variables of the bc command, scale . 

4. scale variable lets us to define the precision we would like to have it.
$ echo "scale=2;$x/$y" | bc
1.71
   Since the scale is defined as 2, we got the result with the right precision.

Let us now look into the other  two special variables of bc, ibase & obase. These 2 variables are used to define the base of the numbers. ibase is used to specify the base of the input number, and obase for the output result.

5. Say now, we want to find the Hex of a decimal number, 80. We use the obase to define the output in hex format:
$ echo "obase=16; 80" | bc
50
6. Similarly, if we now want the result in octal:
$ echo "obase=8;80" | bc
120
7. In binary:
$ echo "obase=2;80" | bc
1010000
8. Now, let us consider we want to convert a binary number to decimal. For this, we need to define the ibase as 2 since the input is binary. obase need not be defined since the result by default is decimal.
$ echo "ibase=2;1010000" | bc
80
9. Similarly, to convert a binary number to hex using bc:
$ echo "obase=16;ibase=2;1010000" | bc
50
10. bc command can also be invoked in the interactive mode. To do this, simply type "bc" from the command prompt:
$ bc
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'.
Once you are in interactive mode, all the above said functions can be done here as well.

 bc is a very useful utility for mathematical operations. Happy calculating!!!
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment