Thursday, September 25, 2008

Bash desk calculator dc help manual


The dc (desk calculator) utility is stack-oriented and uses RPN ("Reverse Polish Notation").

Some of its uses today I explored are:

1) Hex, Binary, Decimal conversion:

Hex of 10

$ echo 10 16 o p | dc
A

Binary of 10

$ echo 10 2 o p | dc
1010

Decimal of C

$ echo C 10 o p | dc
12

here:

"o" sets radix (numerical base) of output.
"p" prints the top of stack.

2) Notation:

(500 % 34) + 234 is represented like this in dc:

$ echo 500 % 34 + 234 | bc
258

$ echo 500 34 % 234 + p | dc
258

p Prints the value on the top of the stack, without altering the stack. A newline is printed after the value.

+ Pops two values off the stack, adds them, and pushes the result. The precision of the result is determined only by the values of
the arguments, and is enough to be exact.

% Pops two values, computes the remainder of the division that the / command would do, and pushes that. The value computed is the
same as that computed by the sequence Sd dld/ Ld*- .


3) Generate RANDOM number between a range using dc:

To generate a RANDOM number between 200 and 300

$ echo $RANDOM 101 % 200 + p | dc

the same can be achieved in a simple way like this:

$ echo $((RANDOM%101+200))

Related post:

- Simple front end for bash bc calculator
- Bash float comparison using bc calculator
- Bash float comparison using bc and awk

No comments:

© Jadu Saikia www.UNIXCL.com