Skip to content

Instantly share code, notes, and snippets.

@twopoint718
Last active April 17, 2023 03:40
Show Gist options
  • Save twopoint718/c82236660fad5ad0a118ea522cb54aa9 to your computer and use it in GitHub Desktop.
Save twopoint718/c82236660fad5ad0a118ea522cb54aa9 to your computer and use it in GitHub Desktop.
UNIX `dc` cheatsheet

DC Cheatsheet

Mathematical operators

Operator Stack effect notes
+ a b -- $a+b$
- a b -- $a-b$
* a b -- $a*b$
/ a b -- $\frac{a}{b}$
% a b -- $mod(a,b)$
~ a b -- $\frac{a}{b}$ $mod(a,b)$ a, b only eval'd once. 2 values pushed
^ a b -- $a^b$
v a -- $\sqrt{a}$
_ a -- $-a$ (underscore) negate value, _5 also ok
b a -- $\lvert a \rvert$ absolute value
| a b c -- $a^b (mod \space c)$ modular exponentiation
$ a -- $truncate(a)$ drop fractional part
@ a b -- a sets a to b digits of precision
H a b -- $a * 10^b$ shift a b digits left
h a b -- $a * 10^{-b}$ shift a b digits right

Logical operators

Operator Stack effect notes
G a b -- $a == b$ 1 if a equals b, otherwise zero
N a -- $a == 0$ 1 if a is zero, else zero
( a b -- $a \lt b$ 1 if a is less than b, else zero
{ a b -- $a \leq b$ 1 if a is less than or equal b, else 0
) a b -- $a \gt b$ 1 if a is greater than b, else zero
} a b -- $a \geq b$ 1 if a is greater than or equal b, else 0
M a b -- $a \land b$ 1 if a and b are nonzero, zero otherwise
m a b -- $a \lor b$ 1 if a or b are nonzero, zero otherwise

Stack manipulation

Operator Stack effect notes
c -- clears the stack
d a -- a a duplicates item on top of stack
r a b -- b a swaps the top two items
R a b -- a Pops the top item from the stack

Register control

A register is named by any single character, r, which follows the operator. Each named register is also its own stack.

Operator Stack effect notes
sr a b -- a (r = b) pops stack and stores item in register r
lr a (r = b) -- a b copies value of r and pushes on the stack
Sr a c (r = b) -- a (r = b c) Pops item, pushes onto the r stack
Lr a (r = b c) -- a c (r = b) Pops r register, pushes onto main stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment