Home
🧮

dc

I’ve been spending a few hours playing with dc(1). I’ve always had a fascination with stack-based programming languages (and concatenated languages in general like The J Programming language), but have yet to work them into my every day set of tools. However, dc is two letters away and can read and write to the terminal in no time at all.

dc (desk calculator) is a reverse-Polish calculator and programming language included in the Unix operating system. It is used to perform calculations on numbers and variables and perform operations which would be difficult or impossible to do by hand. dc is particularly useful for rapid prototyping of algorithms and for interactive experimentation with numbers and variables.

– thank you Notion AI
I’ll collect some notes here as I learn more.

🔗 Basics

Add a value (or values) to the stack.
$ dc
>>> 5
>>> 1 2 3
p – Print the top value of the stack (print? peek?) without affecting it.
>>> p
3
>>> p
3
# – Comments
>>> 4 3 # ignored until end of line
>>> p
3
c – Clear the stack
>>> c
>>> p

Runtime error: stack has too few elements
    Function: (main)
f – View the entire stack
>>> 1 3 5
>>> 6 4
>>> f
4
6
5
3
1
k – Set the decimal precision
>>> 5k 1 7 / p
.14285
+ - * / % – Arithmetic
>>> 5 4 + p
9
>>> 5 4+ 3 *p
27
>>> 81 7 % p
4
>>> 5k 212 40+ 5 9/ * 40- p
99.99860
o – Output base
>>> 3735928559 p # default is base 10
3735928559
>>> 3735928559 16o p
DEADBEEF
>>> 42 2o p
101010
i – Input base
>>> 16i DEADBEEF p
3735928559
>>> 2i 11011 p
27