3 SPDX-License-Identifier: BSD-2-Clause
5 Copyright (c) 2018-2021 Gavin D. Howard and contributors.
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
10 * Redistributions of source code must retain the above copyright notice, this
11 list of conditions and the following disclaimer.
13 * Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.
33 bc - arbitrary-precision decimal arithmetic language and calculator
37 **bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
41 bc(1) is an interactive processor for a language first standardized in 1991 by
42 POSIX. (The current standard is [here][1].) The language provides unlimited
43 precision decimal arithmetic and is somewhat C-like, but there are differences.
44 Such differences will be noted in this document.
46 After parsing and handling options, this bc(1) reads any files given on the
47 command line and executes them before reading from **stdin**.
49 This bc(1) is a drop-in replacement for *any* bc(1), including (and
50 especially) the GNU bc(1). It also has many extensions and extra features beyond
51 other implementations.
53 **Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
54 parse error, it is probably because a word this bc(1) reserves as a keyword is
55 used as the name of a function, variable, or array. To fix that, use the
56 command-line option **-r** *keyword*, where *keyword* is the keyword that is
57 used as a name in the script. For more information, see the **OPTIONS** section.
59 If parsing scripts meant for other bc(1) implementations still does not work,
60 that is a bug and should be reported. See the **BUGS** section.
64 The following are the options that bc(1) accepts.
66 **-g**, **-\-global-stacks**
68 : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks.
70 This has the effect that a copy of the current value of all four are pushed
71 onto a stack for every function call, as well as popped when every function
72 returns. This means that functions can assign to any and all of those
73 globals without worrying that the change will affect other functions.
74 Thus, a hypothetical function named **output(x,b)** that simply printed
75 **x** in base **b** could be written like this:
77 define void output(x, b) {
84 define void output(x, b) {
92 This makes writing functions much easier.
94 (**Note**: the function **output(x,b)** exists in the extended math library.
95 See the **LIBRARY** section.)
97 However, since using this flag means that functions cannot set **ibase**,
98 **obase**, **scale**, or **seed** globally, functions that are made to do so
99 cannot work anymore. There are two possible use cases for that, and each has
102 First, if a function is called on startup to turn bc(1) into a number
103 converter, it is possible to replace that capability with various shell
106 alias d2o="bc -e ibase=A -e obase=8"
107 alias h2b="bc -e ibase=G -e obase=2"
109 Second, if the purpose of a function is to set **ibase**, **obase**,
110 **scale**, or **seed** globally for any other purpose, it could be split
111 into one to four functions (based on how many globals it sets) and each of
112 those functions could return the desired value for a global.
114 For functions that set **seed**, the value assigned to **seed** is not
115 propagated to parent functions. This means that the sequence of
116 pseudo-random numbers that they see will not be the same sequence of
117 pseudo-random numbers that any parent sees. This is only the case once
118 **seed** has been set.
120 If a function desires to not affect the sequence of pseudo-random numbers
121 of its parents, but wants to use the same **seed**, it can use the following
126 If the behavior of this option is desired for every run of bc(1), then users
127 could make sure to define **BC_ENV_ARGS** and include this option (see the
128 **ENVIRONMENT VARIABLES** section for more details).
130 If **-s**, **-w**, or any equivalents are used, this option is ignored.
132 This is a **non-portable extension**.
136 : Prints a usage message and quits.
138 **-i**, **-\-interactive**
140 : Forces interactive mode. (See the **INTERACTIVE MODE** section.)
142 This is a **non-portable extension**.
144 **-L**, **-\-no-line-length**
146 : Disables line length checking and prints numbers without backslashes and
147 newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
148 the **ENVIRONMENT VARIABLES** section).
150 This is a **non-portable extension**.
152 **-l**, **-\-mathlib**
154 : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
155 math library and the extended math library before running any code,
156 including any expressions or files specified on the command line.
158 To learn what is in the libraries, see the **LIBRARY** section.
160 **-P**, **-\-no-prompt**
162 : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
163 See the **TTY MODE** section.) This is mostly for those users that do not
164 want a prompt or are not used to having them in bc(1). Most of those users
165 would want to put this option in **BC_ENV_ARGS** (see the
166 **ENVIRONMENT VARIABLES** section).
168 These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
169 variables (see the **ENVIRONMENT VARIABLES** section).
171 This is a **non-portable extension**.
173 **-R**, **-\-no-read-prompt**
175 : Disables the read prompt in TTY mode. (The read prompt is only enabled in
176 TTY mode. See the **TTY MODE** section.) This is mostly for those users that
177 do not want a read prompt or are not used to having them in bc(1). Most of
178 those users would want to put this option in **BC_ENV_ARGS** (see the
179 **ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
180 lines of bc(1) scripts that prompt for user input.
182 This option does not disable the regular prompt because the read prompt is
183 only used when the **read()** built-in function is called.
185 These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
186 environment variables (see the **ENVIRONMENT VARIABLES** section), but only
189 This is a **non-portable extension**.
191 **-r** *keyword*, **-\-redefine**=*keyword*
193 : Redefines *keyword* in order to allow it to be used as a function, variable,
194 or array name. This is useful when this bc(1) gives parse errors when
195 parsing scripts meant for other bc(1) implementations.
197 The keywords this bc(1) allows to be redefined are:
219 If any of those keywords are used as a function, variable, or array name in
220 a script, use this option with the keyword as the argument. If multiple are
221 used, use this option for all of them; it can be used multiple times.
223 Keywords are *not* redefined when parsing the builtin math library (see the
224 **LIBRARY** section).
226 It is a fatal error to redefine keywords mandated by the POSIX standard. It
227 is a fatal error to attempt to redefine words that this bc(1) does not
232 : This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
233 Without this option, GNU bc(1) prints a copyright header. This bc(1) only
234 prints the copyright header if one or more of the **-v**, **-V**, or
235 **-\-version** options are given.
237 This is a **non-portable extension**.
239 **-s**, **-\-standard**
241 : Process exactly the language defined by the [standard][1] and error if any
244 This is a **non-portable extension**.
246 **-v**, **-V**, **-\-version**
248 : Print the version information (copyright header) and exit.
250 This is a **non-portable extension**.
254 : Like **-s** and **-\-standard**, except that warnings (and not errors) are
255 printed for non-standard extensions and execution continues normally.
257 This is a **non-portable extension**.
259 **-z**, **-\-leading-zeroes**
261 : Makes bc(1) print all numbers greater than **-1** and less than **1**, and
262 not equal to **0**, with a leading zero.
264 This can be set for individual numbers with the **plz(x)**, plznl(x)**,
265 **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
266 the **LIBRARY** section).
268 This is a **non-portable extension**.
270 **-e** *expr*, **-\-expression**=*expr*
272 : Evaluates *expr*. If multiple expressions are given, they are evaluated in
273 order. If files are given as well (see below), the expressions and files are
274 evaluated in the order given. This means that if a file is given before an
275 expression, the file is read in and evaluated first.
277 If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
278 see the **ENVIRONMENT VARIABLES** section), then after processing all
279 expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
280 as an argument at least once to **-f** or **-\-file**, whether on the
281 command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
282 **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
283 or equivalent is given, bc(1) will give a fatal error and exit.
285 This is a **non-portable extension**.
287 **-f** *file*, **-\-file**=*file*
289 : Reads in *file* and evaluates it, line by line, as though it were read
290 through **stdin**. If expressions are also given (see above), the
291 expressions are evaluated in the order given.
293 If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
294 see the **ENVIRONMENT VARIABLES** section), then after processing all
295 expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
296 as an argument at least once to **-f** or **-\-file**. However, if any other
297 **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
298 **-f-** or equivalent is given, bc(1) will give a fatal error and exit.
300 This is a **non-portable extension**.
302 All long options are **non-portable extensions**.
306 If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
307 **-\-expression** options, then bc(1) read from **stdin**.
309 However, there are a few caveats to this.
311 First, **stdin** is evaluated a line at a time. The only exception to this is if
312 the parse cannot complete. That means that starting a string without ending it
313 or starting a function, **if** statement, or loop without ending it will also
314 cause bc(1) to not execute.
316 Second, after an **if** statement, bc(1) doesn't know if an **else** statement
317 will follow, so it will not execute until it knows there will not be an **else**
322 Any non-error output is written to **stdout**. In addition, if history (see the
323 **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
324 both are output to **stdout**.
326 **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
327 error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
328 **stdout** is closed, as in **bc <file> >&-**, it will quit with an error. This
329 is done so that bc(1) can report problems when **stdout** is redirected to a
332 If there are scripts that depend on the behavior of other bc(1) implementations,
333 it is recommended that those scripts be changed to redirect **stdout** to
338 Any error output is written to **stderr**.
340 **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
341 error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
342 **stderr** is closed, as in **bc <file> 2>&-**, it will quit with an error. This
343 is done so that bc(1) can exit with an error code when **stderr** is redirected
346 If there are scripts that depend on the behavior of other bc(1) implementations,
347 it is recommended that those scripts be changed to redirect **stderr** to
352 The syntax for bc(1) programs is mostly C-like, with some differences. This
353 bc(1) follows the [POSIX standard][1], which is a much more thorough resource
354 for the language this bc(1) accepts. This section is meant to be a summary and a
355 listing of all the extensions to the standard.
357 In the sections below, **E** means expression, **S** means statement, and **I**
360 Identifiers (**I**) start with a lowercase letter and can be followed by any
361 number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
362 (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
363 Identifiers with more than one character (letter) are a
364 **non-portable extension**.
366 **ibase** is a global variable determining how to interpret constant numbers. It
367 is the "input" base, or the number base used for interpreting input numbers.
368 **ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
369 (**-\-warn**) flags were not given on the command line, the max allowable value
370 for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
371 **ibase** is **2**. The max allowable value for **ibase** can be queried in
372 bc(1) programs with the **maxibase()** built-in function.
374 **obase** is a global variable determining how to output results. It is the
375 "output" base, or the number base used for outputting numbers. **obase** is
376 initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
377 can be queried in bc(1) programs with the **maxobase()** built-in function. The
378 min allowable value for **obase** is **0**. If **obase** is **0**, values are
379 output in scientific notation, and if **obase** is **1**, values are output in
380 engineering notation. Otherwise, values are output in the specified base.
382 Outputting in scientific and engineering notations are **non-portable
385 The *scale* of an expression is the number of digits in the result of the
386 expression right of the decimal point, and **scale** is a global variable that
387 sets the precision of any operations, with exceptions. **scale** is initially
388 **0**. **scale** cannot be negative. The max allowable value for **scale** is
389 **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
392 bc(1) has both *global* variables and *local* variables. All *local*
393 variables are local to the function; they are parameters or are introduced in
394 the **auto** list of a function (see the **FUNCTIONS** section). If a variable
395 is accessed which is not a parameter or in the **auto** list, it is assumed to
396 be *global*. If a parent function has a *local* variable version of a variable
397 that a child function considers *global*, the value of that *global* variable in
398 the child function is the value of the variable in the parent function, not the
399 value of the actual *global* variable.
401 All of the above applies to arrays as well.
403 The value of a statement that is an expression (i.e., any of the named
404 expressions or operands) is printed unless the lowest precedence operator is an
405 assignment operator *and* the expression is notsurrounded by parentheses.
407 The value that is printed is also assigned to the special variable **last**. A
408 single dot (**.**) may also be used as a synonym for **last**. These are
409 **non-portable extensions**.
411 Either semicolons or newlines may separate statements.
415 There are two kinds of comments:
417 1. Block comments are enclosed in **/\*** and **\*/**.
418 2. Line comments go from **#** until, and not including, the next newline. This
419 is a **non-portable extension**.
423 The following are named expressions in bc(1):
426 2. Array Elements: **I[E]**
431 7. **last** or a single dot (**.**)
433 Numbers 6 and 7 are **non-portable extensions**.
435 The meaning of **seed** is dependent on the current pseudo-random number
436 generator but is guaranteed to not change except for new major versions.
438 The *scale* and sign of the value may be significant.
440 If a previously used **seed** value is assigned to **seed** and used again, the
441 pseudo-random number generator is guaranteed to produce the same sequence of
442 pseudo-random numbers as it did when the **seed** value was previously used.
444 The exact value assigned to **seed** is not guaranteed to be returned if
445 **seed** is queried again immediately. However, if **seed** *does* return a
446 different value, both values, when assigned to **seed**, are guaranteed to
447 produce the same sequence of pseudo-random numbers. This means that certain
448 values assigned to **seed** will *not* produce unique sequences of pseudo-random
449 numbers. The value of **seed** will change after any use of the **rand()** and
450 **irand(E)** operands (see the *Operands* subsection below), except if the
451 parameter passed to **irand(E)** is **0**, **1**, or negative.
453 There is no limit to the length (number of significant decimal digits) or
454 *scale* of the value that can be assigned to **seed**.
456 Variables and arrays do not interfere; users can have arrays named the same as
457 variables. This also applies to functions (see the **FUNCTIONS** section), so a
458 user can have a variable, array, and function that all have the same name, and
459 they will not shadow each other, whether inside of functions or not.
461 Named expressions are required as the operand of **increment**/**decrement**
462 operators and as the left side of **assignment** operators (see the *Operators*
467 The following are valid operands in bc(1):
469 1. Numbers (see the *Numbers* subsection below).
470 2. Array indices (**I[E]**).
471 3. **(E)**: The value of **E** (used to change precedence).
472 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
473 5. **length(E)**: The number of significant decimal digits in **E**. Returns
474 **1** for **0** with no decimal places. If given a string, the length of the
475 string is returned. Passing a string to **length(E)** is a **non-portable
477 6. **length(I[])**: The number of elements in the array **I**. This is a
478 **non-portable extension**.
479 7. **scale(E)**: The *scale* of **E**.
480 8. **abs(E)**: The absolute value of **E**. This is a **non-portable
482 9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
483 the base, the second is the exponent, and the third is the modulus. All
484 three values must be integers. The second argument must be non-negative. The
485 third argument must be non-zero. This is a **non-portable extension**.
486 10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
487 optimization. The first expression is the dividend, and the second is the
488 divisor, which must be non-zero. The return value is the quotient, and the
489 modulus is stored in index **0** of the provided array (the last argument).
490 This is a **non-portable extension**.
491 11. **asciify(E)**: If **E** is a string, returns a string that is the first
492 letter of its argument. If it is a number, calculates the number mod **256**
493 and returns that number as a one-character string. This is a **non-portable
495 12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
496 a non-**void** function (see the *Void Functions* subsection of the
497 **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
498 **I[]**, which will automatically be turned into array references (see the
499 *Array References* subsection of the **FUNCTIONS** section) if the
500 corresponding parameter in the function definition is an array reference.
501 13. **read()**: Reads a line from **stdin** and uses that as an expression. The
502 result of that expression is the result of the **read()** operand. This is a
503 **non-portable extension**.
504 14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
506 15. **maxobase()**: The max allowable **obase**. This is a **non-portable
508 16. **maxscale()**: The max allowable **scale**. This is a **non-portable
510 17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
511 **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
512 18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
513 or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
514 section. This is a **non-portable extension**.
515 19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
516 or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
517 section. This is a **non-portable extension**.
518 20. **rand()**: A pseudo-random integer between **0** (inclusive) and
519 **BC_RAND_MAX** (inclusive). Using this operand will change the value of
520 **seed**. This is a **non-portable extension**.
521 21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
522 value of **E** (exclusive). If **E** is negative or is a non-integer
523 (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see
524 the **RESET** section) while **seed** remains unchanged. If **E** is larger
525 than **BC_RAND_MAX**, the higher bound is honored by generating several
526 pseudo-random integers, multiplying them by appropriate powers of
527 **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that
528 can be generated with this operand is unbounded. Using this operand will
529 change the value of **seed**, unless the value of **E** is **0** or **1**.
530 In that case, **0** is returned, and **seed** is *not* changed. This is a
531 **non-portable extension**.
532 22. **maxrand()**: The max integer returned by **rand()**. This is a
533 **non-portable extension**.
535 The integers generated by **rand()** and **irand(E)** are guaranteed to be as
536 unbiased as possible, subject to the limitations of the pseudo-random number
539 **Note**: The values returned by the pseudo-random number generator with
540 **rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure.
541 This is a consequence of using a seeded pseudo-random number generator. However,
542 they *are* guaranteed to be reproducible with identical **seed** values. This
543 means that the pseudo-random values from bc(1) should only be used where a
544 reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
545 use a non-seeded pseudo-random number generator.
549 Numbers are strings made up of digits, uppercase letters, and at most **1**
550 period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
551 letters are equal to **9** + their position in the alphabet (i.e., **A** equals
552 **10**, or **9+1**). If a digit or letter makes no sense with the current value
553 of **ibase**, they are set to the value of the highest valid digit in **ibase**.
555 Single-character numbers (i.e., **A** alone) take the value that they would have
556 if they were valid digits, regardless of the value of **ibase**. This means that
557 **A** alone always equals decimal **10** and **Z** alone always equals decimal
560 In addition, bc(1) accepts numbers in scientific notation. These have the form
561 **\<number\>e\<integer\>**. The exponent (the portion after the **e**) must be
562 an integer. An example is **1.89237e9**, which is equal to **1892370000**.
563 Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**.
565 Using scientific notation is an error or warning if the **-s** or **-w**,
566 respectively, command-line options (or equivalents) are given.
568 **WARNING**: Both the number and the exponent in scientific notation are
569 interpreted according to the current **ibase**, but the number is still
570 multiplied by **10\^exponent** regardless of the current **ibase**. For example,
571 if **ibase** is **16** and bc(1) is given the number string **FFeA**, the
572 resulting decimal number will be **2550000000000**, and if bc(1) is given the
573 number string **10e-4**, the resulting decimal number will be **0.0016**.
575 Accepting input as scientific notation is a **non-portable extension**.
579 The following arithmetic and logical operators can be used. They are listed in
580 order of decreasing precedence. Operators in the same group have the same
585 : Type: Prefix and Postfix
589 Description: **increment**, **decrement**
597 Description: **negation**, **boolean not**
605 Description: **truncation**
613 Description: **set precision**
621 Description: **power**
629 Description: **multiply**, **divide**, **modulus**
637 Description: **add**, **subtract**
645 Description: **shift left**, **shift right**
647 **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
653 Description: **assignment**
655 **==** **\<=** **\>=** **!=** **\<** **\>**
661 Description: **relational**
669 Description: **boolean and**
677 Description: **boolean or**
679 The operators will be described in more detail below.
683 : The prefix and postfix **increment** and **decrement** operators behave
684 exactly like they would in C. They require a named expression (see the
685 *Named Expressions* subsection) as an operand.
687 The prefix versions of these operators are more efficient; use them where
692 : The **negation** operator returns **0** if a user attempts to negate any
693 expression with the value **0**. Otherwise, a copy of the expression with
694 its sign flipped is returned.
698 : The **boolean not** operator returns **1** if the expression is **0**, or
701 This is a **non-portable extension**.
705 : The **truncation** operator returns a copy of the given expression with all
706 of its *scale* removed.
708 This is a **non-portable extension**.
712 : The **set precision** operator takes two expressions and returns a copy of
713 the first with its *scale* equal to the value of the second expression. That
714 could either mean that the number is returned without change (if the
715 *scale* of the first expression matches the value of the second
716 expression), extended (if it is less), or truncated (if it is more).
718 The second expression must be an integer (no *scale*) and non-negative.
720 This is a **non-portable extension**.
724 : The **power** operator (not the **exclusive or** operator, as it would be in
725 C) takes two expressions and raises the first to the power of the value of
726 the second. The *scale* of the result is equal to **scale**.
728 The second expression must be an integer (no *scale*), and if it is
729 negative, the first value must be non-zero.
733 : The **multiply** operator takes two expressions, multiplies them, and
734 returns the product. If **a** is the *scale* of the first expression and
735 **b** is the *scale* of the second expression, the *scale* of the result is
736 equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
741 : The **divide** operator takes two expressions, divides them, and returns the
742 quotient. The *scale* of the result shall be the value of **scale**.
744 The second expression must be non-zero.
748 : The **modulus** operator takes two expressions, **a** and **b**, and
749 evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
750 result of step 1 to calculate **a-(a/b)\*b** to *scale*
751 **max(scale+scale(b),scale(a))**.
753 The second expression must be non-zero.
757 : The **add** operator takes two expressions, **a** and **b**, and returns the
758 sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
762 : The **subtract** operator takes two expressions, **a** and **b**, and
763 returns the difference, with a *scale* equal to the max of the *scale*s of
768 : The **left shift** operator takes two expressions, **a** and **b**, and
769 returns a copy of the value of **a** with its decimal point moved **b**
772 The second expression must be an integer (no *scale*) and non-negative.
774 This is a **non-portable extension**.
778 : The **right shift** operator takes two expressions, **a** and **b**, and
779 returns a copy of the value of **a** with its decimal point moved **b**
782 The second expression must be an integer (no *scale*) and non-negative.
784 This is a **non-portable extension**.
786 **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
788 : The **assignment** operators take two expressions, **a** and **b** where
789 **a** is a named expression (see the *Named Expressions* subsection).
791 For **=**, **b** is copied and the result is assigned to **a**. For all
792 others, **a** and **b** are applied as operands to the corresponding
793 arithmetic operator and the result is assigned to **a**.
795 The **assignment** operators that correspond to operators that are
796 extensions are themselves **non-portable extensions**.
798 **==** **\<=** **\>=** **!=** **\<** **\>**
800 : The **relational** operators compare two expressions, **a** and **b**, and
801 if the relation holds, according to C language semantics, the result is
802 **1**. Otherwise, it is **0**.
804 Note that unlike in C, these operators have a lower precedence than the
805 **assignment** operators, which means that **a=b\>c** is interpreted as
808 Also, unlike the [standard][1] requires, these operators can appear anywhere
809 any other expressions can be used. This allowance is a
810 **non-portable extension**.
814 : The **boolean and** operator takes two expressions and returns **1** if both
815 expressions are non-zero, **0** otherwise.
817 This is *not* a short-circuit operator.
819 This is a **non-portable extension**.
823 : The **boolean or** operator takes two expressions and returns **1** if one
824 of the expressions is non-zero, **0** otherwise.
826 This is *not* a short-circuit operator.
828 This is a **non-portable extension**.
832 The following items are statements:
835 2. **{** **S** **;** ... **;** **S** **}**
836 3. **if** **(** **E** **)** **S**
837 4. **if** **(** **E** **)** **S** **else** **S**
838 5. **while** **(** **E** **)** **S**
839 6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
840 7. An empty statement
846 13. A string of characters, enclosed in double quotes
847 14. **print** **E** **,** ... **,** **E**
848 15. **stream** **E** **,** ... **,** **E**
849 16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
850 a **void** function (see the *Void Functions* subsection of the
851 **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
852 **I[]**, which will automatically be turned into array references (see the
853 *Array References* subsection of the **FUNCTIONS** section) if the
854 corresponding parameter in the function definition is an array reference.
856 Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
858 Also, as a **non-portable extension**, any or all of the expressions in the
859 header of a for loop may be omitted. If the condition (second expression) is
860 omitted, it is assumed to be a constant **1**.
862 The **break** statement causes a loop to stop iterating and resume execution
863 immediately following a loop. This is only allowed in loops.
865 The **continue** statement causes a loop iteration to stop early and returns to
866 the start of the loop, including testing the loop condition. This is only
869 The **if** **else** statement does the same thing as in C.
871 The **quit** statement causes bc(1) to quit, even if it is on a branch that will
872 not be executed (it is a compile-time command).
874 The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
875 if it is on a branch of an **if** statement that is not executed, bc(1) does not
878 The **limits** statement prints the limits that this bc(1) is subject to. This
879 is like the **quit** statement in that it is a compile-time command.
881 An expression by itself is evaluated and printed, followed by a newline.
883 Both scientific notation and engineering notation are available for printing the
884 results of expressions. Scientific notation is activated by assigning **0** to
885 **obase**, and engineering notation is activated by assigning **1** to
886 **obase**. To deactivate them, just assign a different value to **obase**.
888 Scientific notation and engineering notation are disabled if bc(1) is run with
889 either the **-s** or **-w** command-line options (or equivalents).
891 Printing numbers in scientific notation and/or engineering notation is a
892 **non-portable extension**.
896 If strings appear as a statement by themselves, they are printed without a
899 In addition to appearing as a lone statement by themselves, strings can be
900 assigned to variables and array elements. They can also be passed to functions
901 in variable parameters.
903 If any statement that expects a string is given a variable that had a string
904 assigned to it, the statement acts as though it had received a string.
906 If any math operation is attempted on a string or a variable or array element
907 that has been assigned a string, an error is raised, and bc(1) resets (see the
910 Assigning strings to variables and array elements and passing them to functions
911 are **non-portable extensions**.
915 The "expressions" in a **print** statement may also be strings. If they are, there
916 are backslash escape sequences that are interpreted specially. What those
917 sequences are, and what they cause to be printed, are shown below:
937 Any other character following a backslash causes the backslash and character to
940 Any non-string expression in a print statement shall be assigned to **last**,
941 like any other expression that is printed.
945 The "expressions in a **stream** statement may also be strings.
947 If a **stream** statement is given a string, it prints the string as though the
948 string had appeared as its own statement. In other words, the **stream**
949 statement prints strings normally, without a newline.
951 If a **stream** statement is given a number, a copy of it is truncated and its
952 absolute value is calculated. The result is then printed as though **obase** is
953 **256** and each digit is interpreted as an 8-bit ASCII character, making it a
956 ## Order of Evaluation
958 All expressions in a statment are evaluated left to right, except as necessary
959 to maintain order of operations. This means, for example, assuming that **i** is
960 equal to **0**, in the expression
964 the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
965 at the end of the expression.
967 This includes function arguments. Thus, assuming **i** is equal to **0**, this
968 means that in the expression
972 the first argument passed to **x()** is **0**, and the second argument is **1**,
973 while **i** is equal to **2** before the function starts executing.
977 Function definitions are as follows:
987 Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
988 make a parameter or **auto** var an array, and any **I** in the parameter list
989 may be replaced with **\*I[]** to make a parameter an array reference. Callers
990 of functions that take array references should not put an asterisk in the call;
991 they must be called with just **I[]** like normal array parameters and will be
992 automatically converted into references.
994 As a **non-portable extension**, the opening brace of a **define** statement may
995 appear on the next line.
997 As a **non-portable extension**, the return statement may also be in one of the
1001 2. **return** **(** **)**
1004 The first two, or not specifying a **return** statement, is equivalent to
1005 **return (0)**, unless the function is a **void** function (see the *Void
1006 Functions* subsection below).
1010 Functions can also be **void** functions, defined as follows:
1013 define void I(I,...,I){
1020 They can only be used as standalone expressions, where such an expression would
1021 be printed alone, except in a print statement.
1023 Void functions can only use the first two **return** statements listed above.
1024 They can also omit the return statement entirely.
1026 The word "void" is not treated as a keyword; it is still possible to have
1027 variables, arrays, and functions named **void**. The word "void" is only
1028 treated specially right after the **define** keyword.
1030 This is a **non-portable extension**.
1034 For any array in the parameter list, if the array is declared in the form
1040 it is a **reference**. Any changes to the array in the function are reflected,
1041 when the function returns, to the array that was passed in.
1043 Other than this, all function arguments are passed by value.
1045 This is a **non-portable extension**.
1049 All of the functions below, including the functions in the extended math
1050 library (see the *Extended Library* subsection below), are available when the
1051 **-l** or **-\-mathlib** command-line flags are given, except that the extended
1052 math library is not available when the **-s** option, the **-w** option, or
1053 equivalents are given.
1057 The [standard][1] defines the following functions for the math library:
1061 : Returns the sine of **x**, which is assumed to be in radians.
1063 This is a transcendental function (see the *Transcendental Functions*
1068 : Returns the cosine of **x**, which is assumed to be in radians.
1070 This is a transcendental function (see the *Transcendental Functions*
1075 : Returns the arctangent of **x**, in radians.
1077 This is a transcendental function (see the *Transcendental Functions*
1082 : Returns the natural logarithm of **x**.
1084 This is a transcendental function (see the *Transcendental Functions*
1089 : Returns the mathematical constant **e** raised to the power of **x**.
1091 This is a transcendental function (see the *Transcendental Functions*
1096 : Returns the bessel integer order **n** (truncated) of **x**.
1098 This is a transcendental function (see the *Transcendental Functions*
1103 The extended library is *not* loaded when the **-s**/**-\-standard** or
1104 **-w**/**-\-warn** options are given since they are not part of the library
1105 defined by the [standard][1].
1107 The extended library is a **non-portable extension**.
1111 : Calculates **x** to the power of **y**, even if **y** is not an integer, and
1112 returns the result to the current **scale**.
1114 It is an error if **y** is negative and **x** is **0**.
1116 This is a transcendental function (see the *Transcendental Functions*
1121 : Returns **x** rounded to **p** decimal places according to the rounding mode
1122 [round half away from **0**][3].
1126 : Returns **x** rounded to **p** decimal places according to the rounding mode
1127 [round away from **0**][6].
1131 : Returns the factorial of the truncated absolute value of **x**.
1135 : Returns the permutation of the truncated absolute value of **n** of the
1136 truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
1140 : Returns the combination of the truncated absolute value of **n** of the
1141 truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
1145 : Returns the logarithm base **2** of **x**.
1147 This is a transcendental function (see the *Transcendental Functions*
1152 : Returns the logarithm base **10** of **x**.
1154 This is a transcendental function (see the *Transcendental Functions*
1159 : Returns the logarithm base **b** of **x**.
1161 This is a transcendental function (see the *Transcendental Functions*
1166 : Returns the cube root of **x**.
1170 : Calculates the truncated value of **n**, **r**, and returns the **r**th root
1171 of **x** to the current **scale**.
1173 If **r** is **0** or negative, this raises an error and causes bc(1) to
1174 reset (see the **RESET** section). It also raises an error and causes bc(1)
1175 to reset if **r** is even and **x** is negative.
1179 : Returns the greatest common divisor (factor) of the truncated absolute value
1180 of **a** and the truncated absolute value of **b**.
1184 : Returns the least common multiple of the truncated absolute value of **a**
1185 and the truncated absolute value of **b**.
1189 : Returns **pi** to **p** decimal places.
1191 This is a transcendental function (see the *Transcendental Functions*
1196 : Returns the tangent of **x**, which is assumed to be in radians.
1198 This is a transcendental function (see the *Transcendental Functions*
1203 : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
1204 equal to **0**, it raises an error and causes bc(1) to reset (see the
1205 **RESET** section). Otherwise, if **x** is greater than **0**, it returns
1206 **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
1207 to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
1208 is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
1209 and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
1210 **0**, and **y** is less than **0**, it returns **-pi/2**.
1212 This function is the same as the **atan2()** function in many programming
1215 This is a transcendental function (see the *Transcendental Functions*
1220 : Returns the sine of **x**, which is assumed to be in radians.
1222 This is an alias of **s(x)**.
1224 This is a transcendental function (see the *Transcendental Functions*
1229 : Returns the cosine of **x**, which is assumed to be in radians.
1231 This is an alias of **c(x)**.
1233 This is a transcendental function (see the *Transcendental Functions*
1238 : Returns the tangent of **x**, which is assumed to be in radians.
1240 If **x** is equal to **1** or **-1**, this raises an error and causes bc(1)
1241 to reset (see the **RESET** section).
1243 This is an alias of **t(x)**.
1245 This is a transcendental function (see the *Transcendental Functions*
1250 : Returns the arctangent of **x**, in radians.
1252 This is an alias of **a(x)**.
1254 This is a transcendental function (see the *Transcendental Functions*
1259 : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
1260 equal to **0**, it raises an error and causes bc(1) to reset (see the
1261 **RESET** section). Otherwise, if **x** is greater than **0**, it returns
1262 **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
1263 to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
1264 is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
1265 and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
1266 **0**, and **y** is less than **0**, it returns **-pi/2**.
1268 This function is the same as the **atan2()** function in many programming
1271 This is an alias of **a2(y, x)**.
1273 This is a transcendental function (see the *Transcendental Functions*
1278 : Converts **x** from radians to degrees and returns the result.
1280 This is a transcendental function (see the *Transcendental Functions*
1285 : Converts **x** from degrees to radians and returns the result.
1287 This is a transcendental function (see the *Transcendental Functions*
1292 : Generates a pseudo-random number between **0** (inclusive) and **1**
1293 (exclusive) with the number of decimal digits after the decimal point equal
1294 to the truncated absolute value of **p**. If **p** is not **0**, then
1295 calling this function will change the value of **seed**. If **p** is **0**,
1296 then **0** is returned, and **seed** is *not* changed.
1300 : Generates a pseudo-random number that is between **0** (inclusive) and the
1301 truncated absolute value of **i** (exclusive) with the number of decimal
1302 digits after the decimal point equal to the truncated absolute value of
1303 **p**. If the absolute value of **i** is greater than or equal to **2**, and
1304 **p** is not **0**, then calling this function will change the value of
1305 **seed**; otherwise, **0** is returned and **seed** is not changed.
1309 : Returns **x** with its sign flipped with probability **0.5**. In other
1310 words, it randomizes the sign of **x**.
1314 : Returns a random boolean value (either **0** or **1**).
1318 : Takes the truncated absolute value of both **a** and **b** and calculates
1319 and returns the result of the bitwise **and** operation between them.
1321 If you want to use signed two's complement arguments, use **s2u(x)** to
1326 : Takes the truncated absolute value of both **a** and **b** and calculates
1327 and returns the result of the bitwise **or** operation between them.
1329 If you want to use signed two's complement arguments, use **s2u(x)** to
1334 : Takes the truncated absolute value of both **a** and **b** and calculates
1335 and returns the result of the bitwise **xor** operation between them.
1337 If you want to use signed two's complement arguments, use **s2u(x)** to
1342 : Takes the truncated absolute value of both **a** and **b** and calculates
1343 and returns the result of **a** bit-shifted left by **b** places.
1345 If you want to use signed two's complement arguments, use **s2u(x)** to
1350 : Takes the truncated absolute value of both **a** and **b** and calculates
1351 and returns the truncated result of **a** bit-shifted right by **b** places.
1353 If you want to use signed two's complement arguments, use **s2u(x)** to
1358 : Takes the truncated absolute value of **x** and does a bitwise not as though
1359 it has the same number of bytes as the truncated absolute value of **n**.
1361 If you want to a use signed two's complement argument, use **s2u(x)** to
1366 : Does a bitwise not of the truncated absolute value of **x** as though it has
1367 **8** binary digits (1 unsigned byte).
1369 If you want to a use signed two's complement argument, use **s2u(x)** to
1374 : Does a bitwise not of the truncated absolute value of **x** as though it has
1375 **16** binary digits (2 unsigned bytes).
1377 If you want to a use signed two's complement argument, use **s2u(x)** to
1382 : Does a bitwise not of the truncated absolute value of **x** as though it has
1383 **32** binary digits (4 unsigned bytes).
1385 If you want to a use signed two's complement argument, use **s2u(x)** to
1390 : Does a bitwise not of the truncated absolute value of **x** as though it has
1391 **64** binary digits (8 unsigned bytes).
1393 If you want to a use signed two's complement argument, use **s2u(x)** to
1398 : Does a bitwise not of the truncated absolute value of **x** as though it has
1399 the minimum number of power of two unsigned bytes.
1401 If you want to a use signed two's complement argument, use **s2u(x)** to
1406 : Runs a bit reversal on the truncated absolute value of **x** as though it
1407 has the same number of 8-bit bytes as the truncated absolute value of **n**.
1409 If you want to a use signed two's complement argument, use **s2u(x)** to
1414 : Runs a bit reversal on the truncated absolute value of **x** as though it
1415 has 8 binary digits (1 unsigned byte).
1417 If you want to a use signed two's complement argument, use **s2u(x)** to
1422 : Runs a bit reversal on the truncated absolute value of **x** as though it
1423 has 16 binary digits (2 unsigned bytes).
1425 If you want to a use signed two's complement argument, use **s2u(x)** to
1430 : Runs a bit reversal on the truncated absolute value of **x** as though it
1431 has 32 binary digits (4 unsigned bytes).
1433 If you want to a use signed two's complement argument, use **s2u(x)** to
1438 : Runs a bit reversal on the truncated absolute value of **x** as though it
1439 has 64 binary digits (8 unsigned bytes).
1441 If you want to a use signed two's complement argument, use **s2u(x)** to
1446 : Runs a bit reversal on the truncated absolute value of **x** as though it
1447 has the minimum number of power of two unsigned bytes.
1449 If you want to a use signed two's complement argument, use **s2u(x)** to
1454 : Does a left bitwise rotatation of the truncated absolute value of **x**, as
1455 though it has the same number of unsigned 8-bit bytes as the truncated
1456 absolute value of **n**, by the number of places equal to the truncated
1457 absolute value of **p** modded by the **2** to the power of the number of
1458 binary digits in **n** 8-bit bytes.
1460 If you want to a use signed two's complement argument, use **s2u(x)** to
1465 : Does a left bitwise rotatation of the truncated absolute value of **x**, as
1466 though it has **8** binary digits (**1** unsigned byte), by the number of
1467 places equal to the truncated absolute value of **p** modded by **2** to the
1470 If you want to a use signed two's complement argument, use **s2u(x)** to
1475 : Does a left bitwise rotatation of the truncated absolute value of **x**, as
1476 though it has **16** binary digits (**2** unsigned bytes), by the number of
1477 places equal to the truncated absolute value of **p** modded by **2** to the
1480 If you want to a use signed two's complement argument, use **s2u(x)** to
1485 : Does a left bitwise rotatation of the truncated absolute value of **x**, as
1486 though it has **32** binary digits (**2** unsigned bytes), by the number of
1487 places equal to the truncated absolute value of **p** modded by **2** to the
1490 If you want to a use signed two's complement argument, use **s2u(x)** to
1495 : Does a left bitwise rotatation of the truncated absolute value of **x**, as
1496 though it has **64** binary digits (**2** unsigned bytes), by the number of
1497 places equal to the truncated absolute value of **p** modded by **2** to the
1500 If you want to a use signed two's complement argument, use **s2u(x)** to
1505 : Does a left bitwise rotatation of the truncated absolute value of **x**, as
1506 though it has the minimum number of power of two unsigned 8-bit bytes, by
1507 the number of places equal to the truncated absolute value of **p** modded
1508 by 2 to the power of the number of binary digits in the minimum number of
1511 If you want to a use signed two's complement argument, use **s2u(x)** to
1516 : Does a right bitwise rotatation of the truncated absolute value of **x**, as
1517 though it has the same number of unsigned 8-bit bytes as the truncated
1518 absolute value of **n**, by the number of places equal to the truncated
1519 absolute value of **p** modded by the **2** to the power of the number of
1520 binary digits in **n** 8-bit bytes.
1522 If you want to a use signed two's complement argument, use **s2u(x)** to
1527 : Does a right bitwise rotatation of the truncated absolute value of **x**, as
1528 though it has **8** binary digits (**1** unsigned byte), by the number of
1529 places equal to the truncated absolute value of **p** modded by **2** to the
1532 If you want to a use signed two's complement argument, use **s2u(x)** to
1537 : Does a right bitwise rotatation of the truncated absolute value of **x**, as
1538 though it has **16** binary digits (**2** unsigned bytes), by the number of
1539 places equal to the truncated absolute value of **p** modded by **2** to the
1542 If you want to a use signed two's complement argument, use **s2u(x)** to
1547 : Does a right bitwise rotatation of the truncated absolute value of **x**, as
1548 though it has **32** binary digits (**2** unsigned bytes), by the number of
1549 places equal to the truncated absolute value of **p** modded by **2** to the
1552 If you want to a use signed two's complement argument, use **s2u(x)** to
1557 : Does a right bitwise rotatation of the truncated absolute value of **x**, as
1558 though it has **64** binary digits (**2** unsigned bytes), by the number of
1559 places equal to the truncated absolute value of **p** modded by **2** to the
1562 If you want to a use signed two's complement argument, use **s2u(x)** to
1567 : Does a right bitwise rotatation of the truncated absolute value of **x**, as
1568 though it has the minimum number of power of two unsigned 8-bit bytes, by
1569 the number of places equal to the truncated absolute value of **p** modded
1570 by 2 to the power of the number of binary digits in the minimum number of
1573 If you want to a use signed two's complement argument, use **s2u(x)** to
1578 : Returns the modulus of the truncated absolute value of **x** by **2** to the
1579 power of the multiplication of the truncated absolute value of **n** and
1582 If you want to a use signed two's complement argument, use **s2u(x)** to
1587 : Returns the modulus of the truncated absolute value of **x** by **2** to the
1590 If you want to a use signed two's complement argument, use **s2u(x)** to
1595 : Returns the modulus of the truncated absolute value of **x** by **2** to the
1598 If you want to a use signed two's complement argument, use **s2u(x)** to
1603 : Returns the modulus of the truncated absolute value of **x** by **2** to the
1606 If you want to a use signed two's complement argument, use **s2u(x)** to
1611 : Returns the modulus of the truncated absolute value of **x** by **2** to the
1614 If you want to a use signed two's complement argument, use **s2u(x)** to
1619 : Assumes **t** is a bitwise-reversed number with an extra set bit one place
1620 more significant than the real most significant bit (which was the least
1621 significant bit in the original number). This number is reversed and
1622 returned without the extra set bit.
1624 This function is used to implement other bitwise functions; it is not meant
1625 to be used by users, but it can be.
1629 : If **x** is not equal to **0** and greater that **-1** and less than **1**,
1630 it is printed with a leading zero, regardless of the use of the **-z**
1631 option (see the **OPTIONS** section) and without a trailing newline.
1633 Otherwise, **x** is printed normally, without a trailing newline.
1637 : If **x** is not equal to **0** and greater that **-1** and less than **1**,
1638 it is printed with a leading zero, regardless of the use of the **-z**
1639 option (see the **OPTIONS** section) and with a trailing newline.
1641 Otherwise, **x** is printed normally, with a trailing newline.
1645 : If **x** is not equal to **0** and greater that **-1** and less than **1**,
1646 it is printed without a leading zero, regardless of the use of the **-z**
1647 option (see the **OPTIONS** section) and without a trailing newline.
1649 Otherwise, **x** is printed normally, without a trailing newline.
1653 : If **x** is not equal to **0** and greater that **-1** and less than **1**,
1654 it is printed without a leading zero, regardless of the use of the **-z**
1655 option (see the **OPTIONS** section) and with a trailing newline.
1657 Otherwise, **x** is printed normally, with a trailing newline.
1661 : Returns the numbers of unsigned integer bytes required to hold the truncated
1662 absolute value of **x**.
1666 : Returns the numbers of signed, two's-complement integer bytes required to
1667 hold the truncated value of **x**.
1671 : Returns **x** if it is non-negative. If it *is* negative, then it calculates
1672 what **x** would be as a 2's-complement signed integer and returns the
1673 non-negative integer that would have the same representation in binary.
1677 : Returns **x** if it is non-negative. If it *is* negative, then it calculates
1678 what **x** would be as a 2's-complement signed integer with **n** bytes and
1679 returns the non-negative integer that would have the same representation in
1680 binary. If **x** cannot fit into **n** 2's-complement signed bytes, it is
1685 : Outputs the hexadecimal (base **16**) representation of **x**.
1687 This is a **void** function (see the *Void Functions* subsection of the
1688 **FUNCTIONS** section).
1692 : Outputs the binary (base **2**) representation of **x**.
1694 This is a **void** function (see the *Void Functions* subsection of the
1695 **FUNCTIONS** section).
1699 : Outputs the base **b** representation of **x**.
1701 This is a **void** function (see the *Void Functions* subsection of the
1702 **FUNCTIONS** section).
1706 : Outputs the representation, in binary and hexadecimal, of **x** as an
1707 unsigned integer in as few power of two bytes as possible. Both outputs are
1708 split into bytes separated by spaces.
1710 If **x** is not an integer or is negative, an error message is printed
1711 instead, but bc(1) is not reset (see the **RESET** section).
1713 This is a **void** function (see the *Void Functions* subsection of the
1714 **FUNCTIONS** section).
1718 : Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1719 two's-complement integer in as few power of two bytes as possible. Both
1720 outputs are split into bytes separated by spaces.
1722 If **x** is not an integer, an error message is printed instead, but bc(1)
1723 is not reset (see the **RESET** section).
1725 This is a **void** function (see the *Void Functions* subsection of the
1726 **FUNCTIONS** section).
1730 : Outputs the representation, in binary and hexadecimal, of **x** as an
1731 unsigned integer in **n** bytes. Both outputs are split into bytes separated
1734 If **x** is not an integer, is negative, or cannot fit into **n** bytes, an
1735 error message is printed instead, but bc(1) is not reset (see the **RESET**
1738 This is a **void** function (see the *Void Functions* subsection of the
1739 **FUNCTIONS** section).
1743 : Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1744 two's-complement integer in **n** bytes. Both outputs are split into bytes
1745 separated by spaces.
1747 If **x** is not an integer or cannot fit into **n** bytes, an error message
1748 is printed instead, but bc(1) is not reset (see the **RESET** section).
1750 This is a **void** function (see the *Void Functions* subsection of the
1751 **FUNCTIONS** section).
1755 : Outputs the representation, in binary and hexadecimal, of **x** as an
1756 unsigned integer in **1** byte. Both outputs are split into bytes separated
1759 If **x** is not an integer, is negative, or cannot fit into **1** byte, an
1760 error message is printed instead, but bc(1) is not reset (see the **RESET**
1763 This is a **void** function (see the *Void Functions* subsection of the
1764 **FUNCTIONS** section).
1768 : Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1769 two's-complement integer in **1** byte. Both outputs are split into bytes
1770 separated by spaces.
1772 If **x** is not an integer or cannot fit into **1** byte, an error message
1773 is printed instead, but bc(1) is not reset (see the **RESET** section).
1775 This is a **void** function (see the *Void Functions* subsection of the
1776 **FUNCTIONS** section).
1780 : Outputs the representation, in binary and hexadecimal, of **x** as an
1781 unsigned integer in **2** bytes. Both outputs are split into bytes separated
1784 If **x** is not an integer, is negative, or cannot fit into **2** bytes, an
1785 error message is printed instead, but bc(1) is not reset (see the **RESET**
1788 This is a **void** function (see the *Void Functions* subsection of the
1789 **FUNCTIONS** section).
1793 : Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1794 two's-complement integer in **2** bytes. Both outputs are split into bytes
1795 separated by spaces.
1797 If **x** is not an integer or cannot fit into **2** bytes, an error message
1798 is printed instead, but bc(1) is not reset (see the **RESET** section).
1800 This is a **void** function (see the *Void Functions* subsection of the
1801 **FUNCTIONS** section).
1805 : Outputs the representation, in binary and hexadecimal, of **x** as an
1806 unsigned integer in **4** bytes. Both outputs are split into bytes separated
1809 If **x** is not an integer, is negative, or cannot fit into **4** bytes, an
1810 error message is printed instead, but bc(1) is not reset (see the **RESET**
1813 This is a **void** function (see the *Void Functions* subsection of the
1814 **FUNCTIONS** section).
1818 : Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1819 two's-complement integer in **4** bytes. Both outputs are split into bytes
1820 separated by spaces.
1822 If **x** is not an integer or cannot fit into **4** bytes, an error message
1823 is printed instead, but bc(1) is not reset (see the **RESET** section).
1825 This is a **void** function (see the *Void Functions* subsection of the
1826 **FUNCTIONS** section).
1830 : Outputs the representation, in binary and hexadecimal, of **x** as an
1831 unsigned integer in **8** bytes. Both outputs are split into bytes separated
1834 If **x** is not an integer, is negative, or cannot fit into **8** bytes, an
1835 error message is printed instead, but bc(1) is not reset (see the **RESET**
1838 This is a **void** function (see the *Void Functions* subsection of the
1839 **FUNCTIONS** section).
1843 : Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1844 two's-complement integer in **8** bytes. Both outputs are split into bytes
1845 separated by spaces.
1847 If **x** is not an integer or cannot fit into **8** bytes, an error message
1848 is printed instead, but bc(1) is not reset (see the **RESET** section).
1850 This is a **void** function (see the *Void Functions* subsection of the
1851 **FUNCTIONS** section).
1855 : Outputs the representation of the truncated absolute value of **x** as an
1856 unsigned integer in hexadecimal using **n** bytes. Not all of the value will
1857 be output if **n** is too small.
1859 This is a **void** function (see the *Void Functions* subsection of the
1860 **FUNCTIONS** section).
1862 **binary_uint(x, n)**
1864 : Outputs the representation of the truncated absolute value of **x** as an
1865 unsigned integer in binary using **n** bytes. Not all of the value will be
1866 output if **n** is too small.
1868 This is a **void** function (see the *Void Functions* subsection of the
1869 **FUNCTIONS** section).
1871 **output_uint(x, n)**
1873 : Outputs the representation of the truncated absolute value of **x** as an
1874 unsigned integer in the current **obase** (see the **SYNTAX** section) using
1875 **n** bytes. Not all of the value will be output if **n** is too small.
1877 This is a **void** function (see the *Void Functions* subsection of the
1878 **FUNCTIONS** section).
1880 **output_byte(x, i)**
1882 : Outputs byte **i** of the truncated absolute value of **x**, where **0** is
1883 the least significant byte and **number_of_bytes - 1** is the most
1886 This is a **void** function (see the *Void Functions* subsection of the
1887 **FUNCTIONS** section).
1889 ## Transcendental Functions
1891 All transcendental functions can return slightly inaccurate results (up to 1
1892 [ULP][4]). This is unavoidable, and [this article][5] explains why it is
1893 impossible and unnecessary to calculate exact results for the transcendental
1896 Because of the possible inaccuracy, I recommend that users call those functions
1897 with the precision (**scale**) set to at least 1 higher than is necessary. If
1898 exact results are *absolutely* required, users can double the precision
1899 (**scale**) and then truncate.
1901 The transcendental functions in the standard math library are:
1910 The transcendental functions in the extended math library are:
1928 When bc(1) encounters an error or a signal that it has a non-default handler
1929 for, it resets. This means that several things happen.
1931 First, any functions that are executing are stopped and popped off the stack.
1932 The behavior is not unlike that of exceptions in programming languages. Then
1933 the execution point is set so that any code waiting to execute (after all
1934 functions returned) is skipped.
1936 Thus, when bc(1) resets, it skips any remaining code waiting to be executed.
1937 Then, if it is interactive mode, and the error was not a fatal error (see the
1938 **EXIT STATUS** section), it asks for more input; otherwise, it exits with the
1939 appropriate return code.
1941 Note that this reset behavior is different from the GNU bc(1), which attempts to
1942 start executing the statement right after the one that caused an error.
1946 Most bc(1) implementations use **char** types to calculate the value of **1**
1947 decimal digit at a time, but that can be slow. This bc(1) does something
1950 It uses large integers to calculate more than **1** decimal digit at a time. If
1951 built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
1952 **64**, then each integer has **9** decimal digits. If built in an environment
1953 where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1954 value (the number of decimal digits per large integer) is called
1957 The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
1958 the **limits** statement.
1960 In addition, this bc(1) uses an even larger integer for overflow checking. This
1961 integer type depends on the value of **BC_LONG_BIT**, but is always at least
1962 twice as large as the integer type used to store digits.
1966 The following are the limits on bc(1):
1970 : The number of bits in the **long** type in the environment where bc(1) was
1971 built. This determines how many decimal digits can be stored in a single
1972 large integer (see the **PERFORMANCE** section).
1976 : The number of decimal digits per large integer (see the **PERFORMANCE**
1977 section). Depends on **BC_LONG_BIT**.
1981 : The max decimal number that each large integer can store (see
1982 **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1986 : The max number that the overflow type (see the **PERFORMANCE** section) can
1987 hold. Depends on **BC_LONG_BIT**.
1991 : The maximum output base. Set at **BC_BASE_POW**.
1995 : The maximum size of arrays. Set at **SIZE_MAX-1**.
1999 : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
2003 : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
2007 : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
2011 : The maximum length of a number (in decimal digits), which includes digits
2012 after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
2016 : The maximum integer (inclusive) returned by the **rand()** operand. Set at
2017 **2\^BC_LONG_BIT-1**.
2021 : The maximum allowable exponent (positive or negative). Set at
2022 **BC_OVERFLOW_MAX**.
2026 : The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
2028 The actual values can be queried with the **limits** statement.
2030 These limits are meant to be effectively non-existent; the limits are so large
2031 (at least on 64-bit machines) that there should not be any point at which they
2032 become a problem. In fact, memory should be exhausted before these limits should
2035 # ENVIRONMENT VARIABLES
2037 bc(1) recognizes the following environment variables:
2041 : If this variable exists (no matter the contents), bc(1) behaves as if
2042 the **-s** option was given.
2046 : This is another way to give command-line arguments to bc(1). They should be
2047 in the same format as all other command-line arguments. These are always
2048 processed first, so any files given in **BC_ENV_ARGS** will be processed
2049 before arguments and files given on the command-line. This gives the user
2050 the ability to set up "standard" options and files to be used at every
2051 invocation. The most useful thing for such files to contain would be useful
2052 functions that the user might want every time bc(1) runs.
2054 The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
2055 but it does not understand escape sequences. For example, the string
2056 **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
2057 **"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
2059 The quote parsing will handle either kind of quotes, **'** or **"**. Thus,
2060 if you have a file with any number of single quotes in the name, you can use
2061 double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice
2062 versa if you have a file with double quotes. However, handling a file with
2063 both kinds of quotes in **BC_ENV_ARGS** is not supported due to the
2064 complexity of the parsing, though such files are still supported on the
2065 command-line where the parsing is done by the shell.
2069 : If this environment variable exists and contains an integer that is greater
2070 than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
2071 lines to that length, including the backslash (**\\**). The default line
2074 The special value of **0** will disable line length checking and print
2075 numbers without regard to line length and without backslashes and newlines.
2079 : If this environment variable exists and contains an integer, then a non-zero
2080 value activates the copyright banner when bc(1) is in interactive mode,
2081 while zero deactivates it.
2083 If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
2084 then this environment variable has no effect because bc(1) does not print
2085 the banner when not in interactive mode.
2087 This environment variable overrides the default, which can be queried with
2088 the **-h** or **-\-help** options.
2092 : If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
2093 then this environment variable has no effect because bc(1) exits on
2094 **SIGINT** when not in interactive mode.
2096 However, when bc(1) is in interactive mode, then if this environment
2097 variable exists and contains an integer, a non-zero value makes bc(1) reset
2098 on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
2099 environment variable exists and is *not* an integer, then bc(1) will exit on
2102 This environment variable overrides the default, which can be queried with
2103 the **-h** or **-\-help** options.
2107 : If TTY mode is *not* available (see the **TTY MODE** section), then this
2108 environment variable has no effect.
2110 However, when TTY mode is available, then if this environment variable
2111 exists and contains an integer, then a non-zero value makes bc(1) use TTY
2112 mode, and zero makes bc(1) not use TTY mode.
2114 This environment variable overrides the default, which can be queried with
2115 the **-h** or **-\-help** options.
2119 : If TTY mode is *not* available (see the **TTY MODE** section), then this
2120 environment variable has no effect.
2122 However, when TTY mode is available, then if this environment variable
2123 exists and contains an integer, a non-zero value makes bc(1) use a prompt,
2124 and zero or a non-integer makes bc(1) not use a prompt. If this environment
2125 variable does not exist and **BC_TTY_MODE** does, then the value of the
2126 **BC_TTY_MODE** environment variable is used.
2128 This environment variable and the **BC_TTY_MODE** environment variable
2129 override the default, which can be queried with the **-h** or **-\-help**
2134 bc(1) returns the following exit statuses:
2142 : A math error occurred. This follows standard practice of using **1** for
2143 expected errors, since math errors will happen in the process of normal
2146 Math errors include divide by **0**, taking the square root of a negative
2147 number, using a negative number as a bound for the pseudo-random number
2148 generator, attempting to convert a negative number to a hardware integer,
2149 overflow when converting a number to a hardware integer, overflow when
2150 calculating the size of a number, and attempting to use a non-integer where
2151 an integer is required.
2153 Converting to a hardware integer happens for the second operand of the power
2154 (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**)
2155 operators and their corresponding assignment operators.
2159 : A parse error occurred.
2161 Parse errors include unexpected **EOF**, using an invalid character, failing
2162 to find the end of a string or comment, using a token where it is invalid,
2163 giving an invalid expression, giving an invalid print statement, giving an
2164 invalid function definition, attempting to assign to an expression that is
2165 not a named expression (see the *Named Expressions* subsection of the
2166 **SYNTAX** section), giving an invalid **auto** list, having a duplicate
2167 **auto**/function parameter, failing to find the end of a code block,
2168 attempting to return a value from a **void** function, attempting to use a
2169 variable as a reference, and using any extensions when the option **-s** or
2170 any equivalents were given.
2174 : A runtime error occurred.
2176 Runtime errors include assigning an invalid number to any global (**ibase**,
2177 **obase**, or **scale**), giving a bad expression to a **read()** call,
2178 calling **read()** inside of a **read()** call, type errors, passing the
2179 wrong number of arguments to functions, attempting to call an undefined
2180 function, and attempting to use a **void** function call as a value in an
2185 : A fatal error occurred.
2187 Fatal errors include memory allocation errors, I/O errors, failing to open
2188 files, attempting to use files that do not have only ASCII characters (bc(1)
2189 only accepts ASCII characters), attempting to open a directory as a file,
2190 and giving invalid command-line options.
2192 The exit status **4** is special; when a fatal error occurs, bc(1) always exits
2193 and returns **4**, no matter what mode bc(1) is in.
2195 The other statuses will only be returned when bc(1) is not in interactive mode
2196 (see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the
2197 **RESET** section) and accepts more input when one of those errors occurs in
2198 interactive mode. This is also the case when interactive mode is forced by the
2199 **-i** flag or **-\-interactive** option.
2201 These exit statuses allow bc(1) to be used in shell scripting with error
2202 checking, and its normal behavior can be forced by using the **-i** flag or
2203 **-\-interactive** option.
2207 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
2208 Interactive mode is turned on automatically when both **stdin** and **stdout**
2209 are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
2210 turn it on in other situations.
2212 In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
2213 section), and in normal execution, flushes **stdout** as soon as execution is
2214 done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
2215 depending on the contents of, or default for, the **BC_SIGINT_RESET**
2216 environment variable (see the **ENVIRONMENT VARIABLES** section).
2220 If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
2221 mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
2222 subject to some settings.
2224 If there is the environment variable **BC_TTY_MODE** in the environment (see the
2225 **ENVIRONMENT VARIABLES** section), then if that environment variable contains a
2226 non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
2227 **stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
2228 variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
2231 If the environment variable **BC_TTY_MODE** does *not* exist, the default
2232 setting is used. The default setting can be queried with the **-h** or
2233 **-\-help** options.
2235 TTY mode is different from interactive mode because interactive mode is required
2236 in the [bc(1) specification][1], and interactive mode requires only **stdin**
2237 and **stdout** to be connected to a terminal.
2239 ## Command-Line History
2241 Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
2242 **stdout**, and **stderr** are connected to a TTY and the **BC_TTY_MODE**
2243 environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
2244 do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
2249 If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
2250 can be turned on or off with an environment variable: **BC_PROMPT** (see the
2251 **ENVIRONMENT VARIABLES** section).
2253 If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
2254 the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
2255 to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
2256 prompt will be turned on under the same conditions, except that the **-R** and
2257 **-\-no-read-prompt** options must also not be used.
2259 However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
2260 with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
2261 options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
2262 VARIABLES** and **OPTIONS** sections for more details.
2266 Sending a **SIGINT** will cause bc(1) to do one of two things.
2268 If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
2269 the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
2270 section), or its default, is either not an integer or it is zero, bc(1) will
2273 However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
2274 default is an integer and non-zero, then bc(1) will stop executing the current
2275 input and reset (see the **RESET** section) upon receiving a **SIGINT**.
2277 Note that "current input" can mean one of two things. If bc(1) is processing
2278 input from **stdin** in interactive mode, it will ask for more input. If bc(1)
2279 is processing input from a file in interactive mode, it will stop processing the
2280 file and start processing the next file, if one exists, or ask for input from
2281 **stdin** if no other file exists.
2283 This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
2284 can seem as though bc(1) did not respond to the signal since it will immediately
2285 start executing the next file. This is by design; most files that users execute
2286 when interacting with bc(1) have function definitions, which are quick to parse.
2287 If a file takes a long time to execute, there may be a bug in that file. The
2288 rest of the files could still be executed without problem, allowing the user to
2291 **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
2292 default handler for all other signals. The one exception is **SIGHUP**; in that
2293 case, and only when bc(1) is in TTY mode (see the **TTY MODE** section), a
2294 **SIGHUP** will cause bc(1) to clean up and exit.
2296 # COMMAND LINE HISTORY
2298 bc(1) supports interactive command-line editing.
2300 If bc(1) can be in TTY mode (see the **TTY MODE** section), history can be
2301 enabled. This means that command-line history can only be enabled when
2302 **stdin**, **stdout**, and **stderr** are all connected to a TTY.
2304 Like TTY mode itself, it can be turned on or off with the environment variable
2305 **BC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
2307 If history is enabled, previous lines can be recalled and edited with the arrow
2310 **Note**: tabs are converted to 8 spaces.
2318 bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
2319 specification. The flags **-efghiqsvVw**, all long options, and the extensions
2320 noted above are extensions to that specification.
2322 Note that the specification explicitly says that bc(1) only accepts numbers that
2323 use a period (**.**) as a radix point, regardless of the value of
2328 None are known. Report bugs at https://git.yzena.com/gavin/bc.
2332 Gavin D. Howard <gavin@yzena.com> and contributors.
2334 [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
2335 [2]: https://www.gnu.org/software/bc/
2336 [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
2337 [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
2338 [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
2339 [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero