BC(1) Общие команды BC(1)
NAME
bc - язык арифметики с произвольной точностью и калькулятор
SYNOPSIS
bc [-cCghilPqRsvVw] [--digit-clamp] [--no-digit-clamp]
[--global-stacks] [--help] [--interactive] [--mathlib] [--no-prompt]
[--no-read-prompt] [--quiet] [--standard] [--warn] [--version] [-e
expr] [--expression=expr...] [-f file...] [--file=file...] [file...]
[-I ibase] [--ibase=ibase] [-O obase] [--obase=obase] [-S scale]
[--scale=scale] [-E seed] [--seed=seed]
DESCRIPTION
bc(1) является интерактивным процессором для языка, впервые стандартизированного в
1991 году POSIX. (См. раздел STANDARDS.) Язык предоставляет
арифметику с неограниченной точностью десятичных чисел и в некоторой степени похож на C, но
есть различия. Такие различия будут отмечены в этом
документе.
После разбора и обработки опций, этот bc(1) читает любые файлы, указанные в
командной строке, и выполняет их перед чтением из stdin.
Этот bc(1) является заменой для любого bc(1), включая (и
особенно) GNU bc(1). У него также есть множество расширений и дополнительных
функций по сравнению с другими реализациями.
Примечание: Если выполнение этого bc(1) на любом скрипте, предназначенном для другого bc(1), приводит к
ошибке разбора, вероятно, это потому, что слово, которое этот bc(1) резервирует как
ключевое слово, используется в качестве имени функции, переменной или массива. Чтобы исправить
это, используйте опцию командной строки -r keyword, где keyword -
ключевое слово, которое используется как имя в скрипте. Для получения дополнительной информации
см. раздел OPTIONS.
Если разбор скриптов, предназначенных для других реализаций bc(1), все равно не работает, это
ошибка и должна быть сообщена. См. раздел BUGS.
OPTIONS
Следующие опции принимаются bc(1).
-C, --no-digit-clamp
Отключает ограничение цифр, больших или равных текущему
ibase при разборе чисел.
Это означает, что значение, добавляемое к числу от цифры, всегда равно
значению этой цифры, умноженному на значение ibase,
возведенное в степень позиции цифры, которая начинается с 0
от наименее значимой цифры.
Если эта и/или опции -c или --digit-clamp даны
несколько раз, используется последняя из них.
Эта опция переопределяет переменную окружения BC_DIGIT_CLAMP (см. раздел ENVIRONMENT VARIABLES)
и значение по умолчанию, которое можно запросить с опциями -h или --help.
Это нестандартное расширение.
-c, --digit-clamp
Включает ограничение цифр, больших или равных текущему
ibase при разборе чисел.
Это означает, что значение, добавляемое к числу от цифры, которая больше или равна
ibase, равно значению ibase минус 1, умноженному на значение ibase,
возведенное в степень позиции цифры, которая начинается с 0
от наименее значимой цифры.
Если эта и/или опции -C или --no-digit-clamp даны
несколько раз, используется последняя из них.
Эта опция переопределяет переменную окружения BC_DIGIT_CLAMP (см. раздел ENVIRONMENT VARIABLES)
и значение по умолчанию, которое можно запросить с опциями -h или --help.
Это нестандартное расширение.
-E seed, --seed=seed
Устанавливает встроенную переменную seed на значение seed, предполагая, что
seed в базе 10. Это фатальная ошибка, если seed не является
допустимым числом.
Если несколько экземпляров этой опции даны, используется последняя.
Это нестандартное расширение.
-e expr, --expression=expr
Вычисляет expr. Если несколько выражений даны, они
вычисляются в порядке. Если файлы также даны (см. опции -f и
--file), выражения и файлы вычисляются в порядке, в котором они даны. Это означает, что если файл дан до
выражения, файл читается и вычисляется первым.
Если эта опция дана в командной строке (т.е. не в
BC_ENV_ARGS, см. раздел ENVIRONMENT VARIABLES), то после
обработки всех выражений и файлов, bc(1) выйдет, если не был
дан - (stdin) в качестве аргумента хотя бы раз для -f или --file,
независимо от того, в командной строке или в BC_ENV_ARGS. Однако, если любые другие -e, --expression, -f или --file аргументы даны после
-f- или эквивалентного, bc(1) выдаст фатальную ошибку и
выйдет.
Это нестандартное расширение.
-f file, --file=file
Читает file и вычисляет его построчно, как будто он был
прочитан через stdin. Если выражения также даны (см. опции -e
и --expression), выражения вычисляются в порядке, в котором они даны.
Если эта опция дана в командной строке (т.е. не в
BC_ENV_ARGS, см. раздел ENVIRONMENT VARIABLES), то после
обработки всех выражений и файлов, bc(1) выйдет, если не был
дан - (stdin) в качестве аргумента хотя бы раз для -f или --file.
Однако, если любые другие -e, --expression, -f или --file аргументы даны после
-f- или эквивалентного, bc(1) выдаст фатальную ошибку и
выйдет.
Это нестандартное расширение.
-g, --global-stacks
Превращает глобальные переменные ibase, obase, scale и seed в стеки.
Это означает, что копия текущего значения всех четырех
помещается в стек при каждом вызове функции, а также
извлекается, когда каждая функция возвращается. Это означает, что функции
могут присваивать значения любым и всем этим глобальным переменным без опасений, что
изменение повлияет на другие функции. Таким образом, гипотетическая
функция named output(x,b), которая просто печатает x в базе b, может
быть написана так:
define void output(x, b) {
obase=b
x
}
вместо так:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
Это упрощает написание функций.
(Примечание: функция output(x,b) существует в расширенной математической
библиотеке. См. раздел LIBRARY.)
Однако, поскольку использование этой опции означает, что функции не могут установить
ibase, obase, scale или seed глобально, функции, предназначенные для этого, больше не могут работать. Существуют два возможных случая использования для этого, и каждый имеет решение.
Во-первых, если функция вызывается при запуске для превращения bc(1) в
преобразователь чисел, возможно заменить эту возможность
различными псевдонимами оболочки. Примеры:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Во-вторых, если цель функции - установить ibase, obase,
scale или seed глобально для любой другой цели, она может быть разделена
на одну-четыре функции (на основе того, сколько глобальных переменных она устанавливает)
и каждая из этих функций может возвращать желаемое значение для
глобальной переменной.
Для функций, которые устанавливают seed, значение, присвоенное seed, не
распространяется на родительские функции. Это означает, что последовательность
псевдослучайных чисел, которую они видят, не будет той же последовательностью псевдослучайных чисел, которую видят
любые родители. Это верно только после того, как seed был установлен.
Если функция желает не повлиять на последовательность псевдослучайных чисел
своих родителей, но хочет использовать тот же seed, она
может использовать следующую строку:
seed = seed
Если поведение этой опции желательно для каждого запуска
bc(1), пользователи могут убедиться, что определена BC_ENV_ARGS и в ней
включена эта опция (см. раздел ENVIRONMENT VARIABLES для
получения дополнительной информации).
Если используются -s, -w или любые эквиваленты, эта опция игнорируется.
Это нестандартное расширение.
-h, --help
Печатает сообщение использования и выходит.
-I ibase, --ibase=ibase
Устанавливает встроенную переменную ibase на значение ibase, предполагая, что
ibase в базе 10. Это фатальная ошибка, если ibase не является
допустимым числом.
Если несколько экземпляров этой опции даны, используется последняя.
Это нестандартное расширение.
-i, --interactive
Принудительно включает интерактивный режим. (См. раздел INTERACTIVE MODE.)
Это нестандартное расширение.
-L, --no-line-length
Отключает проверку длины строки и печатает числа без обратных
слэшей и новой строки. Иными словами, эта опция устанавливает
BC_LINE_LENGTH на 0 (см. раздел ENVIRONMENT VARIABLES).
Это нестандартное расширение.
-l, --mathlib
Устанавливает scale (см. раздел SYNTAX) на 20 и загружает встроенную
математическую библиотеку и расширенную математическую библиотеку перед запуском любого
кода, включая любые выражения или файлы, указанные в
командной строке.
Чтобы узнать, что в библиотеках, см. раздел LIBRARY.
-O obase, --obase=obase
Устанавливает встроенную переменную obase на значение obase, предполагая, что
obase в базе 10. Это фатальная ошибка, если obase не является
допустимым числом.
Если несколько экземпляров этой опции даны, используется последняя.
Это нестандартное расширение.
-P, --no-prompt
Отключает подсказку в режиме TTY. (Подсказка включается только в
режиме TTY. См. раздел TTY MODE.) Это в основном для тех
пользователей, которые не хотят подсказки или не привыкли к ним в bc(1).
Большинство таких пользователей захотят добавить эту опцию в
BC_ENV_ARGS (см. раздел ENVIRONMENT VARIABLES).
Эти опции переопределяют переменные окружения BC_PROMPT и BC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES).
Это нестандартное расширение.
-q, --quiet
Эта опция для совместимости с GNU bc(1)
(https://www.gnu.org/software/bc/); она не делает ничего. Без этой
опции, GNU bc(1) печатает заголовок с авторскими правами. Этот bc(1) печатает
заголовок с авторскими правами только если одна или несколько из опций -v, -V или
--version даны, если переменная окружения BC_BANNER установлена и содержит
ненулевое целое число или если этот bc(1) был построен с заголовком по умолчанию. Если это так,
то эта опция предотвращает печать заголовка bc(1).
Это нестандартное расширение.
-R, --no-read-prompt
Отключает подсказку чтения в режиме TTY. (Подсказка чтения включается только в
режиме TTY. См. раздел TTY MODE.) Это в основном для тех
пользователей, которые не хотят подсказки чтения или не привыкли к ним в bc(1).
Большинство таких пользователей захотят добавить эту опцию в
BC_ENV_ARGS (см. раздел ENVIRONMENT VARIABLES). Эта опция также полезна в строках
hash bang скриптов bc(1), которые запрашивают ввод от пользователя.
Эта опция не отключает обычную подсказку, потому что подсказка чтения используется только когда вызывается встроенная функция read().
Эти опции переопределяют переменные окружения BC_PROMPT и BC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES), но только
для подсказки чтения.
Это нестандартное расширение.
-r keyword, --redefine=keyword
Переопределяет keyword, чтобы позволить его использовать как функцию,
переменную или имя массива. Это полезно, когда этот bc(1) выдает
ошибки разбора при разборе скриптов, предназначенных для других реализаций bc(1).
Ключевые слова, которые этот bc(1) позволяет переопределять, следующие:
• abs
• asciify
• continue
• divmod
• else
• halt
• irand
• last
• limits
• maxibase
• maxobase
• maxrand
• maxscale
• modexp
• print
• rand
• read
• seed
• stream
Если любое из этих ключевых слов используется как функция, переменная или
имя массива в скрипте, используйте эту опцию с ключевым словом в качестве
аргумента. Если несколько используются, используйте эту опцию для всех из
них; она может быть использована несколько раз.
Ключевые слова не переопределяются при разборе встроенной математической библиотеки
(см. раздел LIBRARY).
Это фатальная ошибка переопределять ключевые слова, предписанные стандартом POSIX
(см. раздел STANDARDS). Это фатальная ошибка попытаться
переопределить слова, которые этот bc(1) не резервирует как
ключевые слова.
-S scale, --scale=scale
Устанавливает встроенную переменную scale на значение scale, предполагая, что
scale в базе 10. Это фатальная ошибка, если scale не является
допустимым числом.
Если несколько экземпляров этой опции даны, используется последняя.
Это нестандартное расширение.
-s, --standard
Обрабатывает ровно язык, определенный стандартом (см. раздел
STANDARDS), и выдает ошибку, если используются любые расширения.
Это нестандартное расширение.
-v, -V, --version
Печатает информацию о версии (заголовок с авторскими правами) и выходит.
Это нестандартное расширение.
-w, --warn
Как -s и --standard, кроме того, что предупреждения (а не ошибки)
печатаются для нестандартных расширений и выполнение продолжается
нормально.
Это нестандартное расширение.
-z, --leading-zeroes
Делает bc(1) печатать все числа больше -1 и меньше 1,
и не равные 0, с ведущим нулем.
Это можно установить для отдельных чисел с функциями plz(x),
plznl(x), pnlz(x) и pnlznl(x) в расширенной математической
библиотеке (см. раздел LIBRARY).
Это нестандартное расширение.
Все длинные опции являются нестандартными расширениями.
STDIN
Если файлы или выражения не даны опциями -f, --file, -e или --ex‐
pression, то bc(1) читает из stdin.
Однако, есть несколько нюансов.
Во-первых, stdin оценивается построчно. Единственное исключение - если разбор не может
завершиться. Это означает, что начало строки без конца или начало функции, оператора if или цикла без
конца приведет к тому, что bc(1) не выполнит.
Во-вторых, после оператора if, bc(1) не знает, последует ли оператор else, так что он
не выполнит, пока не узнает, что оператора else не будет.
STDOUT
Любая ненулевая выходная информация пишется в stdout. Кроме того, если история
(см. раздел HISTORY) и подсказка (см. раздел TTY MODE) включены, оба выводятся в stdout.
Примечание: В отличие от других реализаций bc(1), этот bc(1) выдаст фатальную
ошибку (см. раздел EXIT STATUS), если не сможет писать в stdout, так что если stdout закрыт, как в bc >&-, он выйдет с ошибкой. Это сделано, чтобы bc(1) мог сообщать о проблемах, когда stdout перенаправлен в
файл.
Если есть скрипты, которые зависят от поведения других реализаций bc(1), рекомендуется изменить эти скрипты, чтобы перенаправлять
stdout в /dev/null.
STDERR
Любая выходная информация об ошибках пишется в stderr.
Примечание: В отличие от других реализаций bc(1), этот bc(1) выдаст фатальную
ошибку (см. раздел EXIT STATUS), если не сможет писать в stderr, так что если stderr закрыт, как в bc 2>&-, он выйдет с ошибкой. Это сделано, чтобы bc(1) мог выйти с кодом ошибки, когда stderr перенаправлен в
файл.
Если есть скрипты, которые зависят от поведения других реализаций bc(1), рекомендуется изменить эти скрипты, чтобы перенаправлять
stderr в /dev/null.
SYNTAX
Синтаксис программ bc(1) в основном похож на C, с некоторыми различиями.
Этот bc(1) следует стандарту POSIX (см. раздел STANDARDS),
который является более thorough ресурсом для языка, который принимает этот bc(1). Этот раздел предназначен для того, чтобы быть кратким обзором и списком всех
расширений к стандарту.
В разделах ниже E означает выражение, S означает оператор, а I
означает идентификатор.
Идентификаторы (I) начинаются с маленькой буквы и могут быть followed любым числом (до BC_NAME_MAX-1) маленьких букв (a-z), цифр
(0-9) и подчеркиваний (_). Регулярное выражение - [a-z][a-z0-9_]*. Идентификаторы
с более чем одним символом (буквой) являются нестандартным расширением.
ibase является глобальной переменной, определяющей, как интерпретировать константные числа. Это "input" база, или числовая база, используемая для интерпретации
входных чисел. ibase изначально 10. Если флаги -s (--standard) и -w
(--warn) не даны в командной строке, максимальное допустимое значение для ibase - 36. В противном случае, оно - 16. Минимальное допустимое значение
для ibase - 2. Максимальное допустимое значение для ibase можно запросить в
программах bc(1) с встроенной функцией maxibase().
obase является глобальной переменной, определяющей, как выводить результаты. Это
"output" база, или числовая база, используемая для вывода чисел.
obase изначально 10. Максимальное допустимое значение для obase -
BC_BASE_MAX и может быть запрошено в программах bc(1) с функцией maxobase().
Минимальное допустимое значение для obase - 0. Если obase
равно 0, значения выводятся в научной нотации, а если obase равно 1, значения выводятся в
инженерной нотации. В противном случае, значения выводятся в указанной базе.
Вывод в научной и инженерной нотациях являются нестандартными расширениями.
Масштаб выражения - это количество цифр в результате выражения справа от десятичной точки, и scale является глобальной переменной,
которая устанавливает точность любых операций, с исключениями. scale изначально 0. scale не может быть отрицательным. Максимальное допустимое значение для
scale - BC_SCALE_MAX и может быть запрошено в программах bc(1) с функцией
maxscale().
bc(1) имеет как глобальные переменные, так и локальные переменные. Все локальные переменные локальны для функции; они являются параметрами или введены
в списке auto функции (см. раздел FUNCTIONS). Если доступна переменная, которая не является параметром или в списке auto, предполагается, что она глобальная. Если родительская функция имеет локальную версию переменной, которую дочерняя функция считает глобальной, значение этой глобальной переменной в дочерней функции - значение переменной
в родительской функции, а не значение фактической глобальной переменной.
Все вышеперечисленное применяется и к массивам.
Значение оператора, который является выражением (т.е. любое из именованных выражений или операндов), печатается, если оператор наименьшей приоритетности -
оператор присваивания и выражение не окружено
скобками.
Значение, которое печатается, также присваивается специальной переменной
last. Одиночная точка (.) может также использоваться как синоним для last. Это нестандартное расширение.
Либо точки с запятой, либо новые строки могут разделять операторы.
Comments
Существуют два вида комментариев:
1. Блочные комментарии заключены в /* и */.
2. Строковые комментарии идут от # до, и не включая, следующей новой строки.
Это нестандартное расширение.
Named Expressions
Следующие являются именованными выражениями в bc(1):
1. Переменные: I
2. Элементы массива: I[E]
3. ibase
4. obase
5. scale
6. seed
7. last или одиночная точка (.)
Пункты 6 и 7 являются нестандартными расширениями.
Значение seed зависит от текущего генератора псевдослучайных чисел, но гарантируется, что оно не изменится, кроме как для новых основных версий.
Масштаб и знак значения могут быть значимыми.
Если ранее использованное значение seed присвоено seed и использовано снова, генератор
псевдослучайных чисел гарантируется производить ту же последовательность псевдослучайных чисел, что и при предыдущем использовании значения seed.
Точное значение, присвоенное seed, не гарантируется быть возвращенным, если seed запрошен снова немедленно. Однако, если seed возвращает другое значение, оба значения, когда присвоены seed, гарантируются производить ту же последовательность псевдослучайных чисел. Это означает, что некоторые значения, присвоенные seed, не будут производить уникальные последовательности псевдослучайных чисел. Значение seed изменится после любого использования
операндов rand() и irand(E) (см. подраздел Operands ниже),
кроме если параметр, переданный irand(E), равен 0, 1 или отрицательному.
Нет ограничения на длину (количество значимых десятичных цифр)
или масштаб значения, которое может быть присвоено seed.
Переменные и массивы не мешают; пользователи могут иметь массивы с именами, такими же, как у переменных. Это также применяется к функциям (см. раздел FUNCTIONS), так что пользователь может иметь переменную, массив и функцию, которые все
имеют одно и то же имя, и они не будут затенять друг друга, независимо от того, внутри функций или нет.
Именованные выражения требуются в качестве операнда операторов инкремента/декремента и как левая сторона операторов присваивания (см. подраздел
Operators).
Operands
Следующие являются допустимыми операндами в bc(1):
1. Числа (см. подраздел Numbers ниже).
2. Индексы массива (I[E]).
3. (E): Значение E (используется для изменения приоритета).
4. sqrt(E): Квадратный корень из E. E должно быть неотрицательным.
5. length(E): Количество значимых десятичных цифр в E. Возвращает
1 для 0 без десятичных знаков. Если дано строку, возвращается длина
строки. Передача строки length(E) является
нестандартным расширением.
6. length(I[]): Количество элементов в массиве I. Это нестандартное
расширение.
7. scale(E): Масштаб E.
8. abs(E): Абсолютное значение E. Это нестандартное расширение.
9. is_number(E): 1, если данный аргумент является числом, 0, если это строка. Это нестандартное расширение.
10. is_string(E): 1, если данный аргумент является строкой, 0, если это число. Это нестандартное расширение.
11. modexp(E, E, E): Модульное возведение в степень, где первое выражение
- база, второе - показатель степени, а третье - модуль. Все три значения должны быть целыми. Второе аргумент должен быть неотрицательным. Третье аргумент должно быть ненулевым. Это нестандартное расширение.
12. divmod(E, E, I[]): Деление и модуль в одной операции. Это для
оптимизации. Первое выражение - делимое, а второе - делитель, который должен быть ненулевым. Возвращаемое значение - частное, а модуль хранится в индексе 0 предоставленного
массива (последний аргумент). Это нестандартное расширение.
13. asciify(E): Если E является строкой, возвращает строку, которая является первым
символом ее аргумента. Если это число, вычисляет число
mod 256 и возвращает это число как строку из одного символа. Это нестандартное расширение.
14. asciify(I[]): Строка, которая состоит из символов, которые бы
resulted от выполнения asciify(E) на каждом элементе массива,
идентифицируемого аргументом. Это позволяет создавать многосимвольные строки
и хранить их. Это нестандартное расширение.
15. I(), I(E), I(E, E) и так далее, где I является идентификатором для
не-void функции (см. подраздел Void Functions раздела FUNC‐
TIONS). Аргумент(ы) E также может быть массивами в форме
I[], которые автоматически преобразуются в ссылки на массивы (см.
подраздел Array References раздела FUNCTIONS), если соответствующий параметр в определении функции - ссылка на массив.
16. read(): Читает строку из stdin и использует ее как выражение.
Результат этого выражения - результат операнда read(). Это нестандартное расширение.
17. maxibase(): Максимальное допустимое ibase. Это нестандартное расширение.
18. maxobase(): Максимальное допустимое obase. Это нестандартное расширение.
19. maxscale(): Максимальное допустимое scale. Это нестандартное расширение.
20. line_length(): Длина строки, установленная с BC_LINE_LENGTH (см. раздел EN‐
VIRONMENT VARIABLES). Это нестандартное расширение.
21. global_stacks(): 0, если глобальные стеки не включены с опциями -g или
--global-stacks, иначе ненулевое. См. раздел OPTIONS. Это нестандартное расширение.
22. leading_zero(): 0, если ведущие нули не включены с опциями -z или
–leading-zeroes, иначе ненулевое. См. раздел OPTIONS. Это нестандартное расширение.
23. rand(): Псевдослучайное целое число между 0 (включительно) и
BC_RAND_MAX (включительно). Использование этого операнда изменит значение
seed. Это нестандартное расширение.
24. irand(E): Псевдослучайное целое число между 0 (включительно) и значением E (исключительно). Если E отрицательное или не целое (масштаб E не 0), возникает ошибка, и bc(1) сбрасывается (см. раздел RE‐
SET), в то время как seed остается неизменным. Если E больше
BC_RAND_MAX, верхний предел соблюдается, генерируя несколько
псевдослучайных целых чисел, умножая их на подходящие степени BC_RAND_MAX+1 и добавляя их вместе. Таким образом, размер целого числа,
которое может быть сгенерировано с этим операндом, неограничен. Использование этого
операнда изменит значение seed, если значение E не 0
или 1. В этом случае возвращается 0, и seed не изменяется. Это
нестандартное расширение.
25. maxrand(): Максимальное целое число, возвращаемое rand(). Это нестандартное расширение.
Целые числа, генерируемые rand() и irand(E), гарантируются быть такими же беспристрастными, насколько возможно, с учетом ограничений генератора псевдослучайных чисел.
Примечание: Значения, возвращаемые генератором псевдослучайных чисел с
rand() и irand(E), гарантируются НЕ быть криптографически безопасными.
Это следствие использования засеянного генератора псевдослучайных чисел.
Однако, они гарантируются быть воспроизводимыми с идентичными значениями seed.
Это означает, что псевдослучайные значения от bc(1) должны использоваться только там, где поток псевдослучайных чисел, воспроизводимый, является
КРИТИЧЕСКИ важным. В любом другом случае используйте несеянный генератор псевдослучайных чисел.
Numbers
Числа являются строками, состоящими из цифр, прописных букв и не более 1
точки для radix. Числа могут иметь до BC_NUM_MAX цифр. Прописные буквы равны 9 плюс их позиция в алфавите,
начиная с 1 (т.е. A равно 10, или 9+1).
Если цифра или буква не имеет смысла с текущим значением ibase
(т.е. они больше или равны текущему значению ibase),
то поведение зависит от наличия опций -c/--digit-clamp или
-C/--no-digit-clamp (см. раздел OPTIONS), наличия и настройки переменной окружения BC_DIGIT_CLAMP (см. раздел ENVI‐
RONMENT VARIABLES) или значения по умолчанию, которое можно запросить с опциями -h/--help.
Если ограничение выключено, то цифры или буквы, которые больше или
равны текущему значению ibase, не изменяются. Вместо этого, их
данное значение умножается на подходящую степень ibase и добавляется
в число. Это означает, что с ibase 3, число AB равно
3^1*A+3^0*B, что равно 3 раза 10 плюс 11, или 41.
Если ограничение включено, то цифры или буквы, которые больше или
равны текущему значению ibase, устанавливаются на значение самой высокой
допустимой цифры в ibase перед умножением на подходящую степень
ibase и добавлением в число. Это означает, что с ibase 3, число AB равно
3^1*2+3^0*2, что равно 3 раза 2 плюс 2, или 8.
Существует одно исключение из ограничения: однозначные числа (т.е. A
в одиночку). Такие числа никогда не ограничиваются и всегда принимают значение, которое они
бы имели в самой высокой возможной ibase. Это означает, что A в одиночку
всегда равно десятичному 10, а Z в одиночку всегда равно десятичному 35. Это поведение предписано стандартом (см. раздел STANDARDS) и предназначено для предоставления простого способа установки текущего ibase (с командой i) независимо от текущего значения ibase.
Если ограничение включено и значение ограниченной цифры needed, используйте ведущий нуль, т.е. для A используйте 0A.
Кроме того, bc(1) принимает числа в научной нотации. Эти имеют
форму <number>e<integer>. Показатель (часть после e)
должен быть целым. Пример - 1.89237e9, что равно
1892370000. Отрицательные показатели также разрешены, так что 4.2890e-3 равно 0.0042890.
Использование научной нотации является ошибкой или предупреждением, если опции -s или -w соответственно даны в командной строке (или эквиваленты).
ПРЕДУПРЕЖДЕНИЕ: Как число, так и показатель в научной нотации интерпретируются в соответствии с текущим ibase, но число все равно умножается на 10^exponent независимо от текущего ibase. Например, если ibase равно 16 и bc(1) дано строковое число FFeA, результирующее десятичное число будет 2550000000000, а если bc(1) дано строковое число 10e-4, результирующее десятичное число будет 0.0016.
Принятие ввода в научной нотации является нестандартным расширением.
Operators
Следующие арифметические и логические операторы могут быть использованы. Они перечислены в порядке убывания приоритета. Операторы в одной группе
имеют одинаковый приоритет.
++ -- Тип: Префиксный и постфиксный
Ассоциативность: Нет
Описание: инкремент, декремент
- ! Тип: Префиксный
Ассоциативность: Нет
Описание: отрицание, логическое не
$ Тип: Постфиксный
Ассоциативность: Нет
Описание: усечение
@ Тип: Бинарный
Ассоциативность: Справа
Описание: установка точности
^ Тип: Бинарный
Ассоциативность: Справа
Описание: возведение в степень
* / % Тип: Бинарный
Ассоциативность: Слева
Описание: умножение, деление, модуль
+ - Тип: Бинарный
Ассоциативность: Слева
Описание: сложение, вычитание
<< >> Тип: Бинарный
Ассоциативность: Слева
Описание: сдвиг влево, сдвиг вправо
= <<= >>= += -= *= /= %= ^= @=
Тип: Бинарный
Ассоциативность: Справа
Описание: присваивание
== <= >= != < >
Тип: Бинарный
Ассоциативность: Слева
Описание: реляционные
&& Тип: Бинарный
Ассоциативность: Слева
Описание: логическое и
|| Тип: Бинарный
Ассоциативность: Слева
Описание: логическое или
Операторы будут описаны более подробно ниже.
++ -- Префиксные и постфиксные операторы инкремента и декремента ведут себя
точно так же, как в C. Они требуют именованного выражения
(см. подраздел Named Expressions) в качестве операнда.
Префиксные версии этих операторов более эффективны; используйте их, где возможно.
- Оператор отрицания возвращает 0, если пользователь пытается отрицать любое выражение со значением 0. В противном случае, возвращается копия выражения с перевернутым знаком.
! Оператор логического не возвращает 1, если выражение равно 0, или 0
в противном случае.
Предупреждение: Этот оператор имеет другой приоритет, чем эквивалентный оператор в GNU bc(1) и других реализациях bc(1)!
Это нестандартное расширение.
$ Оператор усечения возвращает копию данного выражения
без всего его масштаба.
Это нестандартное расширение.
@ Оператор установки точности принимает два выражения и возвращает копию
первого с масштабом, равным значению второго выражения. Это могло бы означать, что число возвращается без изменений (если масштаб первого выражения совпадает со значением второго выражения), расширено (если оно меньше) или усечено (если оно больше).
Второе выражение должно быть целым (без масштаба) и неотрицательным.
Это нестандартное расширение.
^ Оператор возведения в степень (не оператор исключающего или, как это было бы в C) принимает два выражения и возводит первое в степень значения второго. Масштаб результата равен scale.
Второе выражение должно быть целым (без масштаба), и если оно
отрицательное, первое значение должно быть ненулевым.
* Оператор умножения принимает два выражения, умножает их,
и возвращает произведение. Если a - масштаб первого выражения, а b - масштаб второго выражения, масштаб результата равен min(a+b,max(scale,a,b)), где min() и max() возвращают очевидные значения.
/ Оператор деления принимает два выражения, делит их и возвращает частное. Масштаб результата будет равен значению scale.
Второе выражение должно быть ненулевым.
% Оператор модуля принимает два выражения, a и b, и оценивает их путем 1) Вычисления a/b до текущего масштаба и 2) Использования результата шага 1 для расчета a-(a/b)*b до масштаба
max(scale+scale(b),scale(a)).
Второе выражение должно быть ненулевым.
+ Оператор сложения принимает два выражения, a и b, и возвращает сумму, с масштабом, равным максимуму масштабов a и b.
- Оператор вычитания принимает два выражения, a и b, и возвращает разность, с масштабом, равным максимуму масштабов a и b.
<< Оператор сдвига влево принимает два выражения, a и b, и возвращает копию значения a с десятичной точкой, перемещенной b
позиций вправо.
Второе выражение должно быть целым (без масштаба) и неотрицательным.
Это нестандартное расширение.
>> Оператор сдвига вправо принимает два выражения, a и b, и возвращает копию значения a с десятичной точкой, перемещенной b
позиций влево.
Второе выражение должно быть целым (без масштаба) и неотрицательным.
Это нестандартное расширение.
= <<= >>= += -= *= /= %= ^= @=
Операторы присваивания принимают два выражения, a и b, где a
является именованным выражением (см. подраздел Named Expressions).
Для =, b копируется и результат присваивается a. Для всех
остальных, a и b применяются как операнды к соответствующему
арифметическому оператору и результат присваивается a.
Операторы присваивания, соответствующие операторам, которые являются расширениями, сами по себе являются нестандартными расширениями.
== <= >= != < >
Реляционные операторы сравнивают два выражения, a и b, и если отношение верно,
согласно семантике языка C, результат равен 1. В противном случае, он равен 0.
Обратите внимание, что в отличие от C, эти операторы имеют меньший приоритет,
чем операторы присваивания, что означает, что a=b>c интерпретируется как (a=b)>c.
Кроме того, в отличие от того, что требует стандарт (см. раздел STANDARDS), эти операторы могут появляться где угодно, где могут использоваться другие выражения. Это разрешение является нестандартным расширением.
&& Оператор логического и принимает два выражения и возвращает 1, если оба выражения ненулевые, 0 в противном случае.
Это не короткозамкнутый оператор.
Это нестандартное расширение.
|| Оператор логического или принимает два выражения и возвращает 1, если одно из выражений ненулевое, 0 в противном случае.
Это не короткозамкнутый оператор.
Это нестандартное расширение.
Statements
Следующие элементы являются операторами:
1. E
2. { S ; ... ; S }
3. if ( E ) S
4. if ( E ) S else S
5. while ( E ) S
6. for ( E ; E ; E ) S
7. Пустой оператор
8. break
9. continue
10. quit
11. halt
12. limits
13. Строка символов, заключенная в двойные кавычки
14. print E , ... , E
15. stream E , ... , E
16. I(), I(E), I(E, E) и так далее, где I является идентификатором для void
функции (см. подраздел Void Functions раздела FUNCTIONS). Аргумент(ы) E также может быть массивами в форме I[], которые
автоматически преобразуются в ссылки на массивы (см.
подраздел Array References раздела FUNCTIONS), если соответствующий параметр в определении функции - ссылка на массив.
Пункты 4, 9, 11, 12, 14, 15 и 16 являются нестандартными расширениями.
Кроме того, как нестандартное расширение, любое или все выражения в заголовке цикла for могут быть omitted. Если условие (второе выражение) omitted, предполагается, что оно равно константе 1.
Оператор break заставляет цикл прекратить итерацию и продолжить выполнение сразу после цикла. Это разрешено только в циклах.
Оператор continue заставляет итерацию цикла прекратить рано и вернуться
к началу цикла, включая проверку условия цикла.
Это разрешено только в циклах.
Оператор if else работает так же, как в C.
Оператор quit заставляет bc(1) выйти, даже если он на ветке, которая
не будет выполнена (это команда времени компиляции).
Предупреждение: Поведение этого bc(1) на quit немного отличается от других реализаций bc(1). Другие реализации bc(1) выйдут как только закончат разбор строки, на которой команда quit. Этот bc(1) выполнит любые завершенные и исполняемые операторы, которые происходят перед оператором quit перед выходом.
В других словах, для кода bc(1) ниже:
for (i = 0; i < 3; ++i) i; quit
Другие реализации bc(1) ничего не напечатают, а этот bc(1)
напечатает 0, 1 и 2 на последовательных строках перед выходом.
Оператор halt заставляет bc(1) выйти, если он выполнен. (В отличие
от quit, если он на ветке оператора if, которая не выполняется,
bc(1) не выйдет.)
Оператор limits печатает ограничения, которым подчиняется этот bc(1).
Это как оператор quit в том, что это команда времени компиляции.
Выражение само по себе оценивается и печатается, за ним следует новая
строка.
И научная нотация, и инженерная нотация доступны для
печати результатов выражений. Научная нотация активируется
присваиванием 0 obase, а инженерная нотация активируется присваиванием 1 obase. Чтобы деактивировать их, просто присвойте другое значение obase.
Научная нотация и инженерная нотация отключены, если bc(1) запущен с опциями -s или -w командной строки (или эквивалентами).
Печать чисел в научной нотации и/или инженерной нотации является
нестандартным расширением.
Strings
Если строки появляются как оператор сами по себе, они печатаются без
последующей новой строки.
Кроме того, строки могут быть присвоены переменным и элементам массива. Их также можно передать функциям в переменных параметрах.
Если любой оператор, который ожидает строку, дан переменную, которой была присвоена строка, оператор действует так, как будто он получил строку.
Если любая математическая операция предпринимается на строке или переменной или элементе массива, которому была присвоена строка, возникает ошибка, и bc(1)
сбрасывается (см. раздел RESET).
Присваивание строк переменным и элементам массива и передача их функциям являются нестандартными расширениями.
Print Statement
"Выражения" в операторе print также могут быть строками. Если они
являются, существуют последовательности escape с обратным слэшем, которые интерпретируются
специально. Какие это последовательности и что они вызывают печать, приведено ниже:
\a: \a
\b: \b
\\: \
\e: \
\f: \f
\n: \n
\q: “
\r: \r
\t: \t
Любые другие символы, следующие за обратным слэшем, вызывают печать обратного слэша и символа как есть.
Любое невыражение строки в операторе print будет присвоено
last, как и любое другое выражение, которое печатается.
Stream Statement
Выражения в операторе stream также могут быть строками.
Если оператору stream дана строка, он печатает строку так, как будто
строка появилась как свой собственный оператор. Иными словами, оператор stream печатает строки нормально, без новой строки.
Если оператору stream дано число, копия его усекается и
вычисляется его абсолютное значение. Результат затем печатается так, как будто
obase равно 256 и каждая цифра интерпретируется как 8-битный символ ASCII,
делая его потоком байтов.
Order of Evaluation
Все выражения в операторе оцениваются слева направо, кроме как необходимо для поддержания порядка операций. Это означает, например,
предполагая, что i равно 0, в выражении
a[i++] = i++
первый (или 0-й) элемент a устанавливается в 1, и i равно 2 в конце
выражения.
Это включает аргументы функций. Таким образом, предполагая, что i равно 0, это
означает, что в выражении
x(i++, i++)
первый аргумент, переданный x(), равен 0, а второй аргумент равен 1,
в то время как i равно 2 перед тем, как функция начнет выполняться.
FUNCTIONS
Определения функций выглядят так:
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
Любое I в списке параметров или списке auto может быть заменено на I[] для
превращения параметра или auto var в массив, и любое I в списке параметров
может быть заменено на *I[] для превращения параметра в ссылку на массив.
Вызывающие функции, которые принимают ссылки на массивы, не должны ставить звездочку в вызове; они должны быть вызваны с просто I[] как нормальные параметры массива и будут автоматически преобразованы в ссылки.
Как нестандартное расширение, открывающая фигурная скобка оператора define может появляться на следующей строке.
Как нестандартное расширение, оператор return также может быть в одной из
следующих форм:
1. return
2. return ( )
3. return E
Первые два, или не указание оператора return, эквивалентно
return (0), если функция не является void функцией (см. подраздел Void Functions ниже).
Void Functions
Функции также могут быть void функциями, определенными так:
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
Их можно использовать только как отдельные выражения, где такое выражение будет напечатано в одиночку, кроме в операторе print.
Void функции могут использовать только первые два оператора return, перечисленных
выше. Они также могут omitted оператор return полностью.
Слово "void" не трактуется как ключевое слово; все еще возможно
иметь переменные, массивы и функции с именем void. Слово "void" трактуется специально только сразу после ключевого слова define.
Это нестандартное расширение.
Array References
Для любого массива в списке параметров, если массив объявлен в форме
*I[]
это ссылка. Любые изменения массива в функции отражаются,
когда функция возвращается, на массив, который был передан.
В остальном, все аргументы функций передаются по значению.
Это нестандартное расширение.
LIBRARY
Все функции ниже, включая функции в расширенной математической библиотеке (см. подраздел Extended Library ниже), доступны
когда даны флаги командной строки -l или --mathlib, кроме того, что расширенная математическая библиотека недоступна, когда даны опции -s, -w или эквиваленты.
Standard Library
Стандарт (см. раздел STANDARDS) определяет следующие функции для математической библиотеки:
s(x) Возвращает синус x, предполагая, что x в радианах.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
c(x) Возвращает косинус x, предполагая, что x в радианах.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
a(x) Возвращает арктангенс x, в радианах.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
l(x) Возвращает натуральный логарифм x.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
e(x) Возвращает математическую константу e, возведенную в степень x.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
j(x, n)
Возвращает бessel целого порядка n (усеченное) x.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
Extended Library
Расширенная библиотека не загружается, когда даны опции -s/--standard или -w/--warn,
поскольку они не являются частью библиотеки, определенной стандартом (см. раздел STANDARDS).
Расширенная библиотека является нестандартным расширением.
p(x, y)
Вычисляет x в степени y, даже если y не целое, и
возвращает результат до текущего масштаба.
Это ошибка, если y отрицательное и x равно 0.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
r(x, p)
Возвращает x, округленное до p десятичных знаков в соответствии с режимом округления половина от 0
(https://en.wikipedia.org/wiki/Round‐
ing#Round_half_away_from_zero).
ceil(x, p)
Возвращает x, округленное до p десятичных знаков в соответствии с режимом округления от 0 (https://en.wikipedia.org/wiki/Round‐
ing#Rounding_away_from_zero).
f(x) Возвращает факториал усеченного абсолютного значения x.
max(a, b)
Возвращает a, если a больше b; в противном случае, возвращает b.
min(a, b)
Возвращает a, если a меньше b; в противном случае, возвращает b.
perm(n, k)
Возвращает перестановку усеченного абсолютного значения n усеченного абсолютного значения k, если k <= n. Если нет, возвращает 0.
comb(n, k)
Возвращает комбинацию усеченного абсолютного значения n усеченного абсолютного значения k, если k <= n. Если нет, возвращает 0.
fib(n) Возвращает число Фибоначчи усеченного абсолютного значения n.
l2(x) Возвращает логарифм по основанию 2 x.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
l10(x) Возвращает логарифм по основанию 10 x.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
log(x, b)
Возвращает логарифм по основанию b x.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
cbrt(x)
Возвращает кубический корень x.
root(x, n)
Вычисляет усеченное значение n, r, и возвращает r-й корень
x до текущего масштаба.
Если r равно 0 или отрицательному, это вызывает ошибку, и bc(1)
сбрасывается (см. раздел RESET). Это также вызывает ошибку и
сбрасывает bc(1), если r четное и x отрицательное.
gcd(a, b)
Возвращает наибольший общий делитель (фактор) усеченного
абсолютного значения a и усеченного абсолютного значения b.
lcm(a, b)
Возвращает наименьшее общее кратное усеченного абсолютного
значения a и усеченного абсолютного значения b.
pi(p) Возвращает pi до p десятичных знаков.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
t(x) Возвращает тангенс x, предполагая, что x в радианах.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
a2(y, x)
Возвращает арктангенс y/x, в радианах. Если и y, и x равны 0, это вызывает ошибку, и bc(1) сбрасывается (см.
раздел RESET). В противном случае, если x больше 0, возвращается a(y/x). Если x меньше 0, и y больше или равно 0, возвращается a(y/x)+pi. Если x меньше 0, и y меньше 0, возвращается a(y/x)-pi. Если x равно 0, и y больше 0, возвращается pi/2. Если x равно 0, и y меньше 0, возвращается -pi/2.
Эта функция такая же, как функция atan2() во многих языках
программирования.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
sin(x) Возвращает синус x, предполагая, что x в радианах.
Это псевдоним s(x).
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
cos(x) Возвращает косинус x, предполагая, что x в радианах.
Это псевдоним c(x).
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
tan(x) Возвращает тангенс x, предполагая, что x в радианах.
Если x равно 1 или -1, это вызывает ошибку, и bc(1)
сбрасывается (см. раздел RESET).
Это псевдоним t(x).
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
atan(x)
Возвращает арктангенс x, в радианах.
Это псевдоним a(x).
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
atan2(y, x)
Возвращает арктангенс y/x, в радианах. Если и y, и x равны 0, это вызывает ошибку, и bc(1) сбрасывается (см.
раздел RESET). В противном случае, если x больше 0, возвращается a(y/x). Если x меньше 0, и y больше или равно 0, возвращается a(y/x)+pi. Если x меньше 0, и y меньше 0, возвращается a(y/x)-pi. Если x равно 0, и y больше 0, возвращается pi/2. Если x равно 0, и y меньше 0, возвращается -pi/2.
Эта функция такая же, как функция atan2() во многих языках
программирования.
Это псевдоним a2(y, x).
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
r2d(x) Преобразует x из радиан в градусы и возвращает результат.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
d2r(x) Преобразует x из градусов в радианы и возвращает результат.
Это трансцендентная функция (см. подраздел Transcendental Func‐
tions ниже).
frand(p)
Генерирует псевдослучайное число между 0 (включительно) и 1
(исключительно) с количеством десятичных цифр после десятичной точки, равным усеченному абсолютному значению p. Если p не 0, то вызов этой функции изменит значение seed. Если p равно 0, возвращается 0, и seed не изменяется.
ifrand(i, p)
Генерирует псевдослучайное число, которое между 0 (включительно)
и усеченным абсолютным значением i (исключительно) с количеством десятичных цифр после десятичной точки, равным усеченному абсолютному значению p. Если абсолютное значение i больше или равно 2, и p не 0, то вызов этой функции изменит значение seed; в противном случае, возвращается 0, и seed не изменяется.
i2rand(a, b)
Берет усеченное значение a и b и использует их как включительные
границы для генерации псевдослучайного целого. Если разница усеченных значений a и b равна 0, то усеченное значение возвращается, и seed не изменяется. В противном случае, эта функция изменит значение seed.
srand(x)
Возвращает x с перевернутым знаком с вероятностью 0.5. Иными словами, оно случайизирует знак x.
brand()
Возвращает случайное логическое значение (либо 0, либо 1).
band(a, b)
Берет усеченное абсолютное значение и b и вычисляет и возвращает результат операции побитового и между ними.
Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
для преобразования.
bor(a, b)
Берет усеченное абсолютное значение и b и вычисляет и возвращает результат операции побитового или между ними.
Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
для преобразования.
bxor(a, b)
Берет усеченное абсолютное значение и b и вычисляет и возвращает результат операции побитового исключающего или между ними.
Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
для преобразования.
bshl(a, b)
Берет усеченное абсолютное значение и b и вычисляет и возвращает результат a, сдвинутого влево на b позиций.
Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
для преобразования.
bshr(a, b)
Берет усеченное абсолютное значение и b и вычисляет и возвращает усеченный результат a, сдвинутого вправо на b позиций.
Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
для преобразования.
bnotn(x, n)
Берет усеченное абсолютное значение x и выполняет побитовое не
так, как будто у него такое же количество байтов, как у усеченного абсолютного значения n.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bnot8(x)
Выполняет побитовое не усеченного абсолютного значения x так,
как будто у него 8 бинарных цифр (1 беззнаковый байт).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bnot16(x)
Выполняет побитовое не усеченного абсолютного значения x так,
как будто у него 16 бинарных цифр (2 беззнаковых байта).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bnot32(x)
Выполняет побитовое не усеченного абсолютного значения x так,
как будто у него 32 бинарных цифр (4 беззнаковых байта).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bnot64(x)
Выполняет побитовое не усеченного абсолютного значения x так,
как будто у него 64 бинарных цифр (8 беззнаковых байтов).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bnot(x)
Выполняет побитовое не усеченного абсолютного значения x так,
как будто у него минимальное количество степеней степени два беззнаковых байтов.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brevn(x, n)
Выполняет реверс битов усеченного абсолютного значения x так,
как будто у него такое же количество 8-битных байтов, как у усеченного абсолютного значения n.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brev8(x)
Выполняет реверс битов усеченного абсолютного значения x так,
как будто у него 8 бинарных цифр (1 беззнаковый байт).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brev16(x)
Выполняет реверс битов усеченного абсолютного значения x так,
как будто у него 16 бинарных цифр (2 беззнаковых байта).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brev32(x)
Выполняет реверс битов усеченного абсолютного значения x так,
как будто у него 32 бинарных цифр (4 беззнаковых байта).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brev64(x)
Выполняет реверс битов усеченного абсолютного значения x так,
как будто у него 64 бинарных цифр (8 беззнаковых байтов).
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brev(x)
Выполняет реверс битов усеченного абсолютного значения x так,
как будто у него минимальное количество степеней степени два беззнаковых байтов.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
broln(x, p, n)
Выполняет левый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него такое же количество беззнаковых 8-битных байтов
как у усеченного абсолютного значения n, на количество позиций
равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в n 8-битных байтах.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brol8(x, p)
Выполняет левый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 8 бинарных цифр (1 беззнаковый байт), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 8.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brol16(x, p)
Выполняет левый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 16 бинарных цифр (2 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 16.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brol32(x, p)
Выполняет левый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 32 бинарных цифр (4 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 32.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brol64(x, p)
Выполняет левый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 64 бинарных цифр (8 беззнаковых байтов), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 64.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brol(x, p)
Выполняет левый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него минимальное количество степеней степени два беззнаковых
8-битных байтов, на количество позиций равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в минимальном количестве 8-битных байтов.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
brorn(x, p, n)
Выполняет правый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него такое же количество беззнаковых 8-битных байтов
как у усеченного абсолютного значения n, на количество позиций
равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в n 8-битных байтах.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bror8(x, p)
Выполняет правый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 8 бинарных цифр (1 беззнаковый байт), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 8.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bror16(x, p)
Выполняет правый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 16 бинарных цифр (2 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 16.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bror32(x, p)
Выполняет правый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 32 бинарных цифр (4 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 32.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bror64(x, p)
Выполняет правый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него 64 бинарных цифр (8 беззнаковых байтов), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 64.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bror(x, p)
Выполняет правый побитовый ротацию усеченного абсолютного значения
x, так, как будто у него минимальное количество степеней степени два беззнаковых
8-битных байтов, на количество позиций равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в минимальном количестве 8-битных байтов.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bmodn(x, n)
Возвращает модуль усеченного абсолютного значения x по 2 в
степени умножения усеченного абсолютного значения n и 8.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bmod8(x, n)
Возвращает модуль усеченного абсолютного значения x по 2 в
степени 8.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bmod16(x, n)
Возвращает модуль усеченного абсолютного значения x по 2 в
степени 16.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bmod32(x, n)
Возвращает модуль усеченного абсолютного значения x по 2 в
степени 32.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bmod64(x, n)
Возвращает модуль усеченного абсолютного значения x по 2 в
степени 64.
Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
s2u(x) для преобразования.
bunrev(t)
Предполагает, что t является числом с реверсированными битами с дополнительным установленным битом на одну позицию более значимую, чем реальный самый значимый бит (который был наименее значимым битом в исходном числе). Это число реверсируется и возвращается без дополнительного установленного бита.
Эта функция используется для реализации других побитовых функций; она не предназначена для использования пользователями, но может быть.
plz(x) Если x не равно 0 и больше -1 и меньше 1, оно
печатается с ведущим нулем, независимо от использования опции -z
(см. раздел OPTIONS) и без последующей новой строки.
В противном случае, x печатается нормально, без последующей новой строки.
plznl(x)
Если x не равно 0 и больше -1 и меньше 1, оно
печатается с ведущим нулем, независимо от использования опции -z
(см. раздел OPTIONS) и с последующей новой строкой.
В противном случае, x печатается нормально, с последующей новой строкой.
pnlz(x)
Если x не равно 0 и больше -1 и меньше 1, оно
печатается без ведущего нуля, независимо от использования опции -z
(см. раздел OPTIONS) и без последующей новой строки.
В противном случае, x печатается нормально, без последующей новой строки.
pnlznl(x)
Если x не равно 0 и больше -1 и меньше 1, оно
печатается без ведущего нуля, независимо от использования опции -z
(см. раздел OPTIONS) и с последующей новой строкой.
В противном случае, x печатается нормально, с последующей новой строкой.
ubytes(x)
Возвращает количество беззнаковых целочисленных байтов, необходимых для хранения
усеченного абсолютного значения x.
sbytes(x)
Возвращает количество знаковых, двухвесовых дополнений целочисленных байтов, необходимых для хранения
усеченного значения x.
s2u(x) Возвращает x, если оно неотрицательное. Если оно отрицательное, то вычисляет, что x было бы как целое со знаком двухвесового дополнения и возвращает неотрицательное целое, которое имело бы то же представление в бинарном виде.
s2un(x,n)
Возвращает x, если оно неотрицательное. Если оно отрицательное, то вычисляет, что x было бы как целое со знаком двухвесового дополнения с n байтами и возвращает неотрицательное целое, которое имело бы то же представление в бинарном виде. Если x не помещается в n знаковых двухвесовых байтов, оно усекается.
hex(x) Выводит шестнадцатеричное (база 16) представление x.
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
binary(x)
Выводит бинарное (база 2) представление x.
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
output(x, b)
Выводит базу b представление x.
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
uint(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как
беззнаковое целое в как можно меньшем количестве степеней степени два байтов. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое или отрицательное, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
int(x) Выводит представление, в бинарном и шестнадцатеричном виде, x как
знаковое, двухвесовое дополнение целое в как можно меньшем количестве степеней степени два байтов. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое, выводится сообщение об ошибке вместо этого, но
bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
uintn(x, n)
Выводит представление, в бинарном и шестнадцатеричном виде, x как
беззнаковое целое в n байтах. Оба вывода разделены на
байты, разделенные пробелами.
Если x не целое, отрицательное или не помещается в n байты,
выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
intn(x, n)
Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в n байтах. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое или не помещается в n байты, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
uint8(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как
беззнаковое целое в 1 байте. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое, отрицательное или не помещается в 1 байт,
выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
int8(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 1 байте. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое или не помещается в 1 байт, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
uint16(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как
беззнаковое целое в 2 байтах. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое, отрицательное или не помещается в 2 байта,
выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
int16(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 2 байтах. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое или не помещается в 2 байта, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
uint32(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как
беззнаковое целое в 4 байтах. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое, отрицательное или не помещается в 4 байта,
выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
int32(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 4 байтах. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое или не помещается в 4 байта, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
uint64(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как
беззнаковое целое в 8 байтах. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое, отрицательное или не помещается в 8 байта,
выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
int64(x)
Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 8 байтах. Оба вывода разделены на байты, разделенные пробелами.
Если x не целое или не помещается в 8 байта, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
hex_uint(x, n)
Выводит представление усеченного абсолютного значения x
как беззнаковое целое в шестнадцатеричном виде с использованием n байтов. Не все значение будет выведено, если n слишком маленькое.
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
binary_uint(x, n)
Выводит представление усеченного абсолютного значения x
как беззнаковое целое в бинарном виде с использованием n байтов. Не все значение будет выведено, если n слишком маленькое.
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
output_uint(x, n)
Выводит представление усеченного абсолютного значения x
как беззнаковое целое в текущей obase (см. раздел SYNTAX)
с использованием n байтов. Не все значение будет выведено, если n слишком маленькое.
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
output_byte(x, i)
Выводит байт i усеченного абсолютного значения x, где 0 -
наименее значимый байт и number_of_bytes - 1 - наиболее значимый байт.
Это void функция (см. подраздел Void Functions раздела
FUNCTIONS).
Transcendental Functions
Все трансцендентные функции могут возвращать слегка неточные результаты, до 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place). Это неизбежно, и статья по адресу https://people.eecs.berke‐
ley.edu/~wkahan/LOG10HAF.TXT объясняет, почему невозможно и ненужно вычислять точные результаты для трансцендентных функций.
Из-за возможной неточности, я рекомендую, чтобы пользователи вызывали эти
функции с точностью (scale), установленной как минимум на 1 выше, чем необходимо. Если точные результаты абсолютно необходимы, пользователи могут удвоить точность (scale) и затем усечь.
Трансцендентные функции в стандартной математической библиотеке:
• s(x)
• c(x)
• a(x)
• l(x)
• e(x)
• j(x, n)
Трансцендентные функции в расширенной математической библиотеке:
• l2(x)
• l10(x)
• log(x, b)
• pi(p)
• t(x)
• a2(y, x)
• sin(x)
• cos(x)
• tan(x)
• atan(x)
• atan2(y, x)
• r2d(x)
• d2r(x)
RESET
Когда bc(1) встречает ошибку или сигнал, для которого у него есть ненулевой обработчик, он сбрасывается. Это означает, что несколько вещей происходит.
Во-первых, любые функции, которые выполняются, останавливаются и снимаются со стека. Поведение не похоже на исключения в языках программирования. Затем точка выполнения устанавливается так, что любой код, ожидающий выполнения (после того, как все функции вернулись), пропускается.
Таким образом, когда bc(1) сбрасывается, он пропускает любой оставшийся код, ожидающий выполнения. Затем, если это интерактивный режим и ошибка не была фатальной ошибкой (см. раздел EXIT STATUS), он запрашивает больше ввода; в противном случае,
он выходит с соответствующим кодом возврата.
Обратите внимание, что это поведение сброса отличается от GNU bc(1), который
пытается начать выполнять оператор сразу после того, который вызвал ошибку.
PERFORMANCE
Большинство реализаций bc(1) используют типы char для вычисления значения 1
десятичной цифры за раз, но это может быть медленно. Этот bc(1) делает что-то другое.
Он использует большие целые числа для вычисления более чем 1 десятичной цифры за раз. Если построен в среде, где BC_LONG_BIT (см. раздел LIMITS) - 64, то каждое целое имеет 9 десятичных цифр. Если построен в среде, где BC_LONG_BIT - 32, то каждое целое имеет 4 десятичных цифры. Это значение (количество десятичных цифр на большое целое) называется BC_BASE_DIGS.
Фактические значения BC_LONG_BIT и BC_BASE_DIGS можно запросить с
оператором limits.
Кроме того, этот bc(1) использует еще большее целое для проверки переполнения. Тип целого зависит от значения BC_LONG_BIT, но всегда как минимум в два раза больше, чем тип целого, используемый для хранения цифр.
LIMITS
Следующие являются ограничениями на bc(1):
BC_LONG_BIT
Количество битов в типе long в среде, где
bc(1) был построен. Это определяет, сколько десятичных цифр может быть
сохранено в одном большом целом (см. раздел PERFORMANCE).
BC_BASE_DIGS
Количество десятичных цифр на большое целое (см. раздел PERFORMANCE). Зависит от BC_LONG_BIT.
BC_BASE_POW
Максимальное десятичное число, которое каждое большое целое может хранить (см.
BC_BASE_DIGS) плюс 1. Зависит от BC_BASE_DIGS.
BC_OVERFLOW_MAX
Максимальное число, которое тип переполнения может удерживать (см. раздел PERFORMANCE). Зависит от BC_LONG_BIT.
BC_BASE_MAX
Максимальная выходная база. Установлено на BC_BASE_POW.
BC_DIM_MAX
Максимальный размер массивов. Установлено на SIZE_MAX-1.
BC_SCALE_MAX
Максимальный scale. Установлено на BC_OVERFLOW_MAX-1.
BC_STRING_MAX
Максимальная длина строк. Установлено на BC_OVERFLOW_MAX-1.
BC_NAME_MAX
Максимальная длина идентификаторов. Установлено на BC_OVERFLOW_MAX-1.
BC_NUM_MAX
Максимальная длина числа (в десятичных цифрах), которая включает
цифры после десятичной точки. Установлено на BC_OVER‐
FLOW_MAX-1.
BC_RAND_MAX
Максимальное целое (включительно), возвращаемое операндом rand(). Установлено на 2^BC_LONG_BIT-1.
Показатель
Максимально допустимый показатель (положительный или отрицательный). Установлено на
BC_OVERFLOW_MAX.
Количество переменных
Максимальное количество переменных/массивов. Установлено на SIZE_MAX-1.
Фактические значения можно запросить с оператором limits.
Эти ограничения предназначены для того, чтобы быть эффективно несуществующими; ограничения такие большие (как минимум на 64-битных машинах), что не должно быть никакого момента, в который они станут проблемой. Фактически, память должна быть исчерпана перед тем, как эти ограничения будут достигнуты.
ENVIRONMENT VARIABLES
Как нестандартные расширения, bc(1) распознает следующие переменные окружения:
POSIXLY_CORRECT
Если эта переменная существует (независимо от содержимого), bc(1) ведет себя
так, как будто дана опция -s.
BC_ENV_ARGS
Это еще один способ передать аргументы командной строки bc(1).
Они должны быть в том же формате, что и все другие аргументы командной строки. Эти всегда обрабатываются первыми, так что любые файлы, данные в BC_ENV_ARGS, будут обработаны перед аргументами и файлами,
данными в командной строке. Это дает пользователю возможность настроить "стандартные" опции и файлы для использования при каждом вызове. Самое полезное для таких файлов - это полезные функции, которые пользователь может захотеть при каждом запуске bc(1).
Код, который парсит BC_ENV_ARGS, правильно обрабатывает quoted
аргументы, но не понимает последовательности escape. Например, строка “/home/gavin/some bc file.bc” будет правильно разобрана, но строка “/home/gavin/some "bc" file.bc”
включит обратные слэши.
Парсинг кавычек будет обрабатывать любой вид кавычек, ' или “.
Таким образом, если у вас есть файл с любым количеством одинарных кавычек в имени, вы можете использовать двойные кавычки как внешние, как в
“some `bc' file.bc”, и наоборот, если у вас есть файл с двойными кавычками. Однако, обработка файла с обоими видами кавычек в BC_ENV_ARGS не поддерживается из-за сложности парсинга, хотя такие файлы все еще поддерживаются в командной строке, где парсинг выполняется оболочкой.
BC_LINE_LENGTH
Если эта переменная окружения существует и содержит целое, которое
больше 1 и меньше UINT16_MAX (2^16-1), bc(1) будет выводить строки этой длины, включая обратный слэш (\).
Длина строки по умолчанию - 70.
Специальное значение 0 отключит проверку длины строки
и напечатает числа без учета длины строки и без обратных
слэшей и новых строк.
BC_BANNER
Если эта переменная окружения существует и содержит целое, то ненулевое значение активирует заголовок с авторскими правами, когда bc(1)
в интерактивном режиме, в то время как нуль деактивирует его.
Если bc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE),
то эта переменная окружения не имеет эффекта, потому что
bc(1) не печатает заголовок, когда не в интерактивном режиме.
Эта переменная окружения переопределяет значение по умолчанию, которое можно
запросить с опциями -h или --help.
BC_SIGINT_RESET
Если bc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE),
то эта переменная окружения не имеет эффекта, потому что
bc(1) выходит на SIGINT, когда не в интерактивном режиме.
Однако, когда bc(1) в интерактивном режиме, то если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) сбрасываться на SIGINT, а не выходить, и нуль заставляет bc(1) выйти. Если эта переменная окружения существует и не является целым, то bc(1) выйдет на SIGINT.
Эта переменная окружения переопределяет значение по умолчанию, которое можно
запросить с опциями -h или --help.
BC_TTY_MODE
Если режим TTY недоступен (см. раздел TTY MODE), то
эта переменная окружения не имеет эффекта.
Однако, когда режим TTY доступен, то если эта переменная окружения существует и содержит целое, то ненулевое значение заставляет bc(1) использовать режим TTY, и нуль заставляет bc(1) не использовать режим TTY.
Эта переменная окружения переопределяет значение по умолчанию, которое можно
запросить с опциями -h или --help.
BC_PROMPT
Если режим TTY недоступен (см. раздел TTY MODE), то
эта переменная окружения не имеет эффекта.
Однако, когда режим TTY доступен, то если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) использовать подсказку, и нуль или нецелое заставляет bc(1) не использовать подсказку. Если эта переменная окружения не существует и BC_TTY_MODE существует, то используется значение переменной BC_TTY_MODE.
Эта переменная окружения и переменная BC_TTY_MODE переопределяют значение по умолчанию, которое можно
запросить с опциями -h или --help.
BC_EXPR_EXIT
Если любые выражения или файлы выражений даны в командной строке с -e, --expression, -f или --file, то если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) выйти после выполнения выражений и файлов выражений, и нулевое значение заставляет bc(1) не выходить.
Эта переменная окружения переопределяет значение по умолчанию, которое можно
запросить с опциями -h или --help.
BC_DIGIT_CLAMP
При разборе чисел и если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) ограничивать цифры, которые больше или равны текущему ibase, так что все такие цифры считаются равными ibase минус 1, и нулевое значение отключает такое ограничение, так что эти цифры всегда равны своему значению, которое умножается на степень ibase.
Это никогда не применяется к однозначным числам, как предписано стандартом
(см. раздел STANDARDS).
Эта переменная окружения переопределяет значение по умолчанию, которое можно
запросить с опциями -h или --help.
EXIT STATUS
bc(1) возвращает следующие коды выхода:
0 Нет ошибки.
1 Произошла математическая ошибка. Это следует стандартной практике использования
1 для ожидаемых ошибок, поскольку математические ошибки будут происходить в процессе нормального выполнения.
Математические ошибки включают деление на 0, извлечение квадратного корня из отрицательного числа, использование отрицательного числа как границы для генератора псевдослучайных чисел, попытку преобразовать отрицательное число в аппаратное целое, переполнение при преобразовании числа в аппаратное целое, переполнение при расчете размера числа и попытку использовать нецелое, где требуется целое.
Преобразование в аппаратное целое происходит для второго операнда
операторов возведения в степень (^), позиций (@), сдвига влево (<<) и сдвига вправо
(>>) и их соответствующих операторов присваивания.
2 Произошла ошибка разбора.
Ошибки разбора включают неожиданный EOF, использование недопустимого символа,
неудачу в нахождении конца строки или комментария, использование токена, где он недопустим, предоставление недопустимого выражения, предоставление недопустимого оператора print, предоставление недопустимого определения функции,
попытку присвоить выражению, которое не является именованным выражением (см. подраздел Named Expressions раздела SYNTAX), предоставление недопустимого списка auto, наличие дублирующего auto/параметра функции, неудачу в нахождении конца блока кода, попытку вернуть значение из void функции, попытку использовать переменную как ссылку и использование любых расширений, когда опция -s или любые эквиваленты даны.
3 Произошла ошибка времени выполнения.
Ошибки времени выполнения включают присваивание недопустимого числа любой глобальной
(ibase, obase или scale), предоставление плохого выражения вызову read(),
вызов read() внутри read(), ошибки типов, передачу неправильного количества аргументов функциям, попытку вызвать неопределенную функцию и попытку использовать вызов void функции как значение в выражении.
4 Произошла фатальная ошибка.
Фатальные ошибки включают ошибки выделения памяти, ошибки I/O, неудачу в открытии файлов, попытку использовать файлы, которые не имеют только символов ASCII (bc(1) принимает только символы ASCII), попытку открыть каталог как файл и предоставление недопустимых опций командной строки.
Код выхода 4 специальный; когда фатальная ошибка происходит, bc(1) всегда
выходит и возвращает 4, независимо от режима, в котором bc(1) находится.
Другие статусы будут возвращены только когда bc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE), поскольку bc(1) сбрасывает свое состояние (см. раздел RESET) и принимает больше ввода, когда одна из этих ошибок происходит в интерактивном режиме. Это также верно, когда интерактивный режим принудительно включен флагом -i или опцией --interactive.
Эти коды выхода позволяют использовать bc(1) в сценариях оболочки с проверкой ошибок, и его нормальное поведение может быть принудительно включено с помощью флага -i или опции --interactive.
INTERACTIVE MODE
Согласно стандарту (см. раздел STANDARDS), bc(1) имеет интерактивный режим и неинтерактивный режим. Интерактивный режим включается автоматически, когда stdin и stdout подключены к терминалу, но флаг -i и опция --interactive могут включить его в других ситуациях.
В интерактивном режиме bc(1) пытается восстановиться от ошибок (см. раздел RE‐
SET), и в нормальном выполнении, сбрасывает stdout как только выполнение завершено для текущего ввода. bc(1) также может сбрасываться на SIGINT вместо выхода, в зависимости от содержимого или значения по умолчанию переменной окружения BC_SIGINT_RESET (см. раздел ENVIRONMENT VARIABLES).
TTY MODE
Если stdin, stdout и stderr все подключены к TTY, то "TTY
режим" считается доступным, и таким образом, bc(1) может включить TTY
режим, с учетом некоторых настроек.
Если существует переменная окружения BC_TTY_MODE в окружении
(см. раздел ENVIRONMENT VARIABLES), то если эта переменная окружения содержит ненулевое целое, bc(1) включит TTY режим, когда stdin, stdout и stderr подключены к TTY. Если переменная BC_TTY_MODE существует, но не является ненулевым целым, то bc(1) не включит TTY режим.
Если переменная окружения BC_TTY_MODE не существует, используется значение по умолчанию.
Значение по умолчанию можно запросить с опциями -h или --help.
Режим TTY отличается от интерактивного режима, потому что интерактивный режим требуется в стандарте bc(1) (см. раздел STANDARDS), и интерактивный режим требует только stdin и stdout, подключенных к терминалу.
Command-Line History
История командной строки включается только если доступен режим TTY (см. раздел TTY MODE), история может быть включена. Это означает, что историю командной строки можно включить только, когда stdin, stdout и stderr подключены к TTY.
Как и сам режим TTY, его можно включить или выключить с переменной окружения BC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES).
Если история включена, предыдущие строки можно вспомнить и отредактировать со стрелочными клавишами.
Примечание: табы преобразуются в 8 пробелов.
LOCALES
Этот bc(1) поставляется с поддержкой добавления сообщений об ошибках для разных локалей и таким образом, поддерживает LC_MESSAGES.
SEE ALSO
dc(1)
STANDARDS
bc(1) соответствует спецификации IEEE Std 1003.1-2017 (“POSIX.1-2017”)
по адресу https://pubs.opengroup.org/onlinepubs/9699919799/utili‐
ties/bc.html . Флаги -efghiqsvVw, все длинные опции и
расширения, отмеченные выше, являются расширениями к этой спецификации.
Кроме того, поведение quit реализует интерпретацию
спецификации, которая отличается от всех известных реализаций.
Для получения дополнительной информации см. подраздел Statements раздела SYNTAX.
Обратите внимание, что спецификация явно говорит, что bc(1) принимает только числа, которые используют точку (.) как десятичную точку, независимо от значения LC_NUMERIC.
Этот bc(1) поддерживает сообщения об ошибках для разных локалей, и таким образом, он
поддерживает LC_MESSAGES.
BUGS
До версии 6.1.0 этот bc(1) имел неправильное поведение для оператора quit.
Другие ошибки не известны. Сообщайте об ошибках по адресу https://git.gavin‐
howard.com/gavin/bc .
AUTHORS
Gavin D. Howard ⟨gavin@gavinhoward.com⟩ и contributors.
BC(1) General Commands Manual BC(1)
NAME
bc - arbitrary-precision decimal arithmetic language and calculator
SYNOPSIS
bc [-cCghilPqRsvVw] [--digit-clamp] [--no-digit-clamp]
[--global-stacks] [--help] [--interactive] [--mathlib] [--no-prompt]
[--no-read-prompt] [--quiet] [--standard] [--warn] [--version] [-e
expr] [--expression=expr...] [-f file...] [--file=file...] [file...]
[-I ibase] [--ibase=ibase] [-O obase] [--obase=obase] [-S scale]
[--scale=scale] [-E seed] [--seed=seed]
DESCRIPTION
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX. (See the STANDARDS section.) The language provides
unlimited precision decimal arithmetic and is somewhat C-like, but
there are differences. Such differences will be noted in this
document.
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from stdin.
This bc(1) is a drop-in replacement for any bc(1), including (and
especially) the GNU bc(1). It also has many extensions and extra
features beyond other implementations.
Note: If running this bc(1) on any script meant for another bc(1) gives
a parse error, it is probably because a word this bc(1) reserves as a
keyword is used as the name of a function, variable, or array. To fix
that, use the command-line option -r keyword, where keyword is the
keyword that is used as a name in the script. For more information,
see the OPTIONS section.
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported. See the BUGS section.
OPTIONS
The following are the options that bc(1) accepts.
-C, --no-digit-clamp
Disables clamping of digits greater than or equal to the current
ibase when parsing numbers.
This means that the value added to a number from a digit is
always that digit’s value multiplied by the value of ibase
raised to the power of the digit’s position, which starts from 0
at the least significant digit.
If this and/or the -c or --digit-clamp options are given
multiple times, the last one given is used.
This option overrides the BC_DIGIT_CLAMP environment variable
(see the ENVIRONMENT VARIABLES section) and the default, which
can be queried with the -h or --help options.
This is a non-portable extension.
-c, --digit-clamp
Enables clamping of digits greater than or equal to the current
ibase when parsing numbers.
This means that digits that the value added to a number from a
digit that is greater than or equal to the ibase is the value of
ibase minus 1 all multiplied by the value of ibase raised to the
power of the digit’s position, which starts from 0 at the least
significant digit.
If this and/or the -C or --no-digit-clamp options are given
multiple times, the last one given is used.
This option overrides the BC_DIGIT_CLAMP environment variable
(see the ENVIRONMENT VARIABLES section) and the default, which
can be queried with the -h or --help options.
This is a non-portable extension.
-E seed, --seed=seed
Sets the builtin variable seed to the value seed assuming that
seed is in base 10. It is a fatal error if seed is not a valid
number.
If multiple instances of this option are given, the last is
used.
This is a non-portable extension.
-e expr, --expression=expr
Evaluates expr. If multiple expressions are given, they are
evaluated in order. If files are given as well (see the -f and
--file options), the expressions and files are evaluated in the
order given. This means that if a file is given before an
expression, the file is read in and evaluated first.
If this option is given on the command-line (i.e., not in
BC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after
processing all expressions and files, bc(1) will exit, unless -
(stdin) was given as an argument at least once to -f or --file,
whether on the command-line or in BC_ENV_ARGS. However, if any
other -e, --expression, -f, or --file arguments are given after
-f- or equivalent is given, bc(1) will give a fatal error and
exit.
This is a non-portable extension.
-f file, --file=file
Reads in file and evaluates it, line by line, as though it were
read through stdin. If expressions are also given (see the -e
and --expression options), the expressions are evaluated in the
order given.
If this option is given on the command-line (i.e., not in
BC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after
processing all expressions and files, bc(1) will exit, unless -
(stdin) was given as an argument at least once to -f or --file.
However, if any other -e, --expression, -f, or --file arguments
are given after -f- or equivalent is given, bc(1) will give a
fatal error and exit.
This is a non-portable extension.
-g, --global-stacks
Turns the globals ibase, obase, scale, and seed into stacks.
This has the effect that a copy of the current value of all four
are pushed onto a stack for every function call, as well as
popped when every function returns. This means that functions
can assign to any and all of those globals without worrying that
the change will affect other functions. Thus, a hypothetical
function named output(x,b) that simply printed x in base b could
be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
(Note: the function output(x,b) exists in the extended math li‐
brary. See the LIBRARY section.)
However, since using this flag means that functions cannot set
ibase, obase, scale, or seed globally, functions that are made
to do so cannot work anymore. There are two possible use cases
for that, and each has a solution.
First, if a function is called on startup to turn bc(1) into a
number converter, it is possible to replace that capability with
various shell aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set ibase, obase,
scale, or seed globally for any other purpose, it could be split
into one to four functions (based on how many globals it sets)
and each of those functions could return the desired value for a
global.
For functions that set seed, the value assigned to seed is not
propagated to parent functions. This means that the sequence of
pseudo-random numbers that they see will not be the same se‐
quence of pseudo-random numbers that any parent sees. This is
only the case once seed has been set.
If a function desires to not affect the sequence of pseudo-ran‐
dom numbers of its parents, but wants to use the same seed, it
can use the following line:
seed = seed
If the behavior of this option is desired for every run of
bc(1), then users could make sure to define BC_ENV_ARGS and in‐
clude this option (see the ENVIRONMENT VARIABLES section for
more details).
If -s, -w, or any equivalents are used, this option is ignored.
This is a non-portable extension.
-h, --help
Prints a usage message and exits.
-I ibase, --ibase=ibase
Sets the builtin variable ibase to the value ibase assuming that
ibase is in base 10. It is a fatal error if ibase is not a
valid number.
If multiple instances of this option are given, the last is
used.
This is a non-portable extension.
-i, --interactive
Forces interactive mode. (See the INTERACTIVE MODE section.)
This is a non-portable extension.
-L, --no-line-length
Disables line length checking and prints numbers without back‐
slashes and newlines. In other words, this option sets
BC_LINE_LENGTH to 0 (see the ENVIRONMENT VARIABLES section).
This is a non-portable extension.
-l, --mathlib
Sets scale (see the SYNTAX section) to 20 and loads the included
math library and the extended math library before running any
code, including any expressions or files specified on the com‐
mand line.
To learn what is in the libraries, see the LIBRARY section.
-O obase, --obase=obase
Sets the builtin variable obase to the value obase assuming that
obase is in base 10. It is a fatal error if obase is not a
valid number.
If multiple instances of this option are given, the last is
used.
This is a non-portable extension.
-P, --no-prompt
Disables the prompt in TTY mode. (The prompt is only enabled in
TTY mode. See the TTY MODE section.) This is mostly for those
users that do not want a prompt or are not used to having them
in bc(1). Most of those users would want to put this option in
BC_ENV_ARGS (see the ENVIRONMENT VARIABLES section).
These options override the BC_PROMPT and BC_TTY_MODE environment
variables (see the ENVIRONMENT VARIABLES section).
This is a non-portable extension.
-q, --quiet
This option is for compatibility with the GNU bc(1)
(https://www.gnu.org/software/bc/); it is a no-op. Without this
option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the -v, -V, or
--version options are given unless the BC_BANNER environment
variable is set and contains a non-zero integer or if this bc(1)
was built with the header displayed by default. If any of that
is the case, then this option does prevent bc(1) from printing
the header.
This is a non-portable extension.
-R, --no-read-prompt
Disables the read prompt in TTY mode. (The read prompt is only
enabled in TTY mode. See the TTY MODE section.) This is mostly
for those users that do not want a read prompt or are not used
to having them in bc(1). Most of those users would want to put
this option in BC_ENV_ARGS (see the ENVIRONMENT VARIABLES sec‐
tion). This option is also useful in hash bang lines of bc(1)
scripts that prompt for user input.
This option does not disable the regular prompt because the read
prompt is only used when the read() built-in function is called.
These options do override the BC_PROMPT and BC_TTY_MODE environ‐
ment variables (see the ENVIRONMENT VARIABLES section), but only
for the read prompt.
This is a non-portable extension.
-r keyword, --redefine=keyword
Redefines keyword in order to allow it to be used as a function,
variable, or array name. This is useful when this bc(1) gives
parse errors when parsing scripts meant for other bc(1) imple‐
mentations.
The keywords this bc(1) allows to be redefined are:
• abs
• asciify
• continue
• divmod
• else
• halt
• irand
• last
• limits
• maxibase
• maxobase
• maxrand
• maxscale
• modexp
• print
• rand
• read
• seed
• stream
If any of those keywords are used as a function, variable, or
array name in a script, use this option with the keyword as the
argument. If multiple are used, use this option for all of
them; it can be used multiple times.
Keywords are not redefined when parsing the builtin math library
(see the LIBRARY section).
It is a fatal error to redefine keywords mandated by the POSIX
standard (see the STANDARDS section). It is a fatal error to
attempt to redefine words that this bc(1) does not reserve as
keywords.
-S scale, --scale=scale
Sets the builtin variable scale to the value scale assuming that
scale is in base 10. It is a fatal error if scale is not a
valid number.
If multiple instances of this option are given, the last is
used.
This is a non-portable extension.
-s, --standard
Process exactly the language defined by the standard (see the
STANDARDS section) and error if any extensions are used.
This is a non-portable extension.
-v, -V, --version
Print the version information (copyright header) and exits.
This is a non-portable extension.
-w, --warn
Like -s and --standard, except that warnings (and not errors)
are printed for non-standard extensions and execution continues
normally.
This is a non-portable extension.
-z, --leading-zeroes
Makes bc(1) print all numbers greater than -1 and less than 1,
and not equal to 0, with a leading zero.
This can be set for individual numbers with the plz(x),
plznl(x), pnlz(x), and pnlznl(x) functions in the extended math
library (see the LIBRARY section).
This is a non-portable extension.
All long options are non-portable extensions.
STDIN
If no files or expressions are given by the -f, --file, -e, or --ex‐
pression options, then bc(1) reads from stdin.
However, there are a few caveats to this.
First, stdin is evaluated a line at a time. The only exception to this
is if the parse cannot complete. That means that starting a string
without ending it or starting a function, if statement, or loop without
ending it will also cause bc(1) to not execute.
Second, after an if statement, bc(1) doesn’t know if an else statement
will follow, so it will not execute until it knows there will not be an
else statement.
STDOUT
Any non-error output is written to stdout. In addition, if history
(see the HISTORY section) and the prompt (see the TTY MODE section) are
enabled, both are output to stdout.
Note: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the EXIT STATUS section) if it cannot write to stdout, so if
stdout is closed, as in bc >&-, it will quit with an error. This is
done so that bc(1) can report problems when stdout is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) imple‐
mentations, it is recommended that those scripts be changed to redirect
stdout to /dev/null.
STDERR
Any error output is written to stderr.
Note: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the EXIT STATUS section) if it cannot write to stderr, so if
stderr is closed, as in bc 2>&-, it will quit with an error. This is
done so that bc(1) can exit with an error code when stderr is redi‐
rected to a file.
If there are scripts that depend on the behavior of other bc(1) imple‐
mentations, it is recommended that those scripts be changed to redirect
stderr to /dev/null.
SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX standard (see the STANDARDS section),
which is a much more thorough resource for the language this bc(1) ac‐
cepts. This section is meant to be a summary and a listing of all the
extensions to the standard.
In the sections below, E means expression, S means statement, and I
means identifier.
Identifiers (I) start with a lowercase letter and can be followed by
any number (up to BC_NAME_MAX-1) of lowercase letters (a-z), digits
(0-9), and underscores (_). The regex is [a-z][a-z0-9_]*. Identifiers
with more than one character (letter) are a non-portable extension.
ibase is a global variable determining how to interpret constant num‐
bers. It is the “input” base, or the number base used for interpreting
input numbers. ibase is initially 10. If the -s (--standard) and -w
(--warn) flags were not given on the command line, the max allowable
value for ibase is 36. Otherwise, it is 16. The min allowable value
for ibase is 2. The max allowable value for ibase can be queried in
bc(1) programs with the maxibase() built-in function.
obase is a global variable determining how to output results. It is
the “output” base, or the number base used for outputting numbers.
obase is initially 10. The max allowable value for obase is
BC_BASE_MAX and can be queried in bc(1) programs with the maxobase()
built-in function. The min allowable value for obase is 0. If obase
is 0, values are output in scientific notation, and if obase is 1, val‐
ues are output in engineering notation. Otherwise, values are output
in the specified base.
Outputting in scientific and engineering notations are non-portable ex‐
tensions.
The scale of an expression is the number of digits in the result of the
expression right of the decimal point, and scale is a global variable
that sets the precision of any operations, with exceptions. scale is
initially 0. scale cannot be negative. The max allowable value for
scale is BC_SCALE_MAX and can be queried in bc(1) programs with the
maxscale() built-in function.
bc(1) has both global variables and local variables. All local vari‐
ables are local to the function; they are parameters or are introduced
in the auto list of a function (see the FUNCTIONS section). If a vari‐
able is accessed which is not a parameter or in the auto list, it is
assumed to be global. If a parent function has a local variable ver‐
sion of a variable that a child function considers global, the value of
that global variable in the child function is the value of the variable
in the parent function, not the value of the actual global variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence opera‐
tor is an assignment operator and the expression is notsurrounded by
parentheses.
The value that is printed is also assigned to the special variable
last. A single dot (.) may also be used as a synonym for last. These
are non-portable extensions.
Either semicolons or newlines may separate statements.
Comments
There are two kinds of comments:
1. Block comments are enclosed in /* and */.
2. Line comments go from # until, and not including, the next newline.
This is a non-portable extension.
Named Expressions
The following are named expressions in bc(1):
1. Variables: I
2. Array Elements: I[E]
3. ibase
4. obase
5. scale
6. seed
7. last or a single dot (.)
Numbers 6 and 7 are non-portable extensions.
The meaning of seed is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major ver‐
sions.
The scale and sign of the value may be significant.
If a previously used seed value is assigned to seed and used again, the
pseudo-random number generator is guaranteed to produce the same se‐
quence of pseudo-random numbers as it did when the seed value was pre‐
viously used.
The exact value assigned to seed is not guaranteed to be returned if
seed is queried again immediately. However, if seed does return a dif‐
ferent value, both values, when assigned to seed, are guaranteed to
produce the same sequence of pseudo-random numbers. This means that
certain values assigned to seed will not produce unique sequences of
pseudo-random numbers. The value of seed will change after any use of
the rand() and irand(E) operands (see the Operands subsection below),
except if the parameter passed to irand(E) is 0, 1, or negative.
There is no limit to the length (number of significant decimal digits)
or scale of the value that can be assigned to seed.
Variables and arrays do not interfere; users can have arrays named the
same as variables. This also applies to functions (see the FUNCTIONS
section), so a user can have a variable, array, and function that all
have the same name, and they will not shadow each other, whether inside
of functions or not.
Named expressions are required as the operand of increment/decrement
operators and as the left side of assignment operators (see the Opera‐
tors subsection).
Operands
The following are valid operands in bc(1):
1. Numbers (see the Numbers subsection below).
2. Array indices (I[E]).
3. (E): The value of E (used to change precedence).
4. sqrt(E): The square root of E. E must be non-negative.
5. length(E): The number of significant decimal digits in E. Returns
1 for 0 with no decimal places. If given a string, the length of
the string is returned. Passing a string to length(E) is a
non-portable extension.
6. length(I[]): The number of elements in the array I. This is a
non-portable extension.
7. scale(E): The scale of E.
8. abs(E): The absolute value of E. This is a non-portable extension.
9. is_number(E): 1 if the given argument is a number, 0 if it is a
string. This is a non-portable extension.
10. is_string(E): 1 if the given argument is a string, 0 if it is a
number. This is a non-portable extension.
11. modexp(E, E, E): Modular exponentiation, where the first expression
is the base, the second is the exponent, and the third is the modu‐
lus. All three values must be integers. The second argument must
be non-negative. The third argument must be non-zero. This is a
non-portable extension.
12. divmod(E, E, I[]): Division and modulus in one operation. This is
for optimization. The first expression is the dividend, and the
second is the divisor, which must be non-zero. The return value is
the quotient, and the modulus is stored in index 0 of the provided
array (the last argument). This is a non-portable extension.
13. asciify(E): If E is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number
mod 256 and returns that number as a one-character string. This is
a non-portable extension.
14. asciify(I[]): A string that is made up of the characters that would
result from running asciify(E) on each element of the array identi‐
fied by the argument. This allows creating multi-character strings
and storing them. This is a non-portable extension.
15. I(), I(E), I(E, E), and so on, where I is an identifier for a
non-void function (see the Void Functions subsection of the FUNC‐
TIONS section). The E argument(s) may also be arrays of the form
I[], which will automatically be turned into array references (see
the Array References subsection of the FUNCTIONS section) if the
corresponding parameter in the function definition is an array ref‐
erence.
16. read(): Reads a line from stdin and uses that as an expression.
The result of that expression is the result of the read() operand.
This is a non-portable extension.
17. maxibase(): The max allowable ibase. This is a non-portable exten‐
sion.
18. maxobase(): The max allowable obase. This is a non-portable exten‐
sion.
19. maxscale(): The max allowable scale. This is a non-portable exten‐
sion.
20. line_length(): The line length set with BC_LINE_LENGTH (see the EN‐
VIRONMENT VARIABLES section). This is a non-portable extension.
21. global_stacks(): 0 if global stacks are not enabled with the -g or
--global-stacks options, non-zero otherwise. See the OPTIONS sec‐
tion. This is a non-portable extension.
22. leading_zero(): 0 if leading zeroes are not enabled with the -z or
–leading-zeroes options, non-zero otherwise. See the OPTIONS sec‐
tion. This is a non-portable extension.
23. rand(): A pseudo-random integer between 0 (inclusive) and
BC_RAND_MAX (inclusive). Using this operand will change the value
of seed. This is a non-portable extension.
24. irand(E): A pseudo-random integer between 0 (inclusive) and the
value of E (exclusive). If E is negative or is a non-integer (E’s
scale is not 0), an error is raised, and bc(1) resets (see the RE‐
SET section) while seed remains unchanged. If E is larger than
BC_RAND_MAX, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
BC_RAND_MAX+1, and adding them together. Thus, the size of integer
that can be generated with this operand is unbounded. Using this
operand will change the value of seed, unless the value of E is 0
or 1. In that case, 0 is returned, and seed is not changed. This
is a non-portable extension.
25. maxrand(): The max integer returned by rand(). This is a non-por‐
table extension.
The integers generated by rand() and irand(E) are guaranteed to be as
unbiased as possible, subject to the limitations of the pseudo-random
number generator.
Note: The values returned by the pseudo-random number generator with
rand() and irand(E) are guaranteed to NOT be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they are guaranteed to be reproducible with identical seed
values. This means that the pseudo-random values from bc(1) should
only be used where a reproducible stream of pseudo-random numbers is
ESSENTIAL. In any other case, use a non-seeded pseudo-random number
generator.
Numbers
Numbers are strings made up of digits, uppercase letters, and at most 1
period for a radix. Numbers can have up to BC_NUM_MAX digits. Upper‐
case letters are equal to 9 plus their position in the alphabet, start‐
ing from 1 (i.e., A equals 10, or 9+1).
If a digit or letter makes no sense with the current value of ibase
(i.e., they are greater than or equal to the current value of ibase),
then the behavior depends on the existence of the -c/--digit-clamp or
-C/--no-digit-clamp options (see the OPTIONS section), the existence
and setting of the BC_DIGIT_CLAMP environment variable (see the ENVI‐
RONMENT VARIABLES section), or the default, which can be queried with
the -h/--help option.
If clamping is off, then digits or letters that are greater than or
equal to the current value of ibase are not changed. Instead, their
given value is multiplied by the appropriate power of ibase and added
into the number. This means that, with an ibase of 3, the number AB is
equal to 3^1*A+3^0*B, which is 3 times 10 plus 11, or 41.
If clamping is on, then digits or letters that are greater than or
equal to the current value of ibase are set to the value of the highest
valid digit in ibase before being multiplied by the appropriate power
of ibase and added into the number. This means that, with an ibase of
3, the number AB is equal to 3^1*2+3^0*2, which is 3 times 2 plus 2, or
8.
There is one exception to clamping: single-character numbers (i.e., A
alone). Such numbers are never clamped and always take the value they
would have in the highest possible ibase. This means that A alone al‐
ways equals decimal 10 and Z alone always equals decimal 35. This be‐
havior is mandated by the standard (see the STANDARDS section) and is
meant to provide an easy way to set the current ibase (with the i com‐
mand) regardless of the current value of ibase.
If clamping is on, and the clamped value of a character is needed, use
a leading zero, i.e., for A, use 0A.
In addition, bc(1) accepts numbers in scientific notation. These have
the form <number>e<integer>. The exponent (the portion after the e)
must be an integer. An example is 1.89237e9, which is equal to
1892370000. Negative exponents are also allowed, so 4.2890e-3 is equal
to 0.0042890.
Using scientific notation is an error or warning if the -s or -w, re‐
spectively, command-line options (or equivalents) are given.
WARNING: Both the number and the exponent in scientific notation are
interpreted according to the current ibase, but the number is still
multiplied by 10^exponent regardless of the current ibase. For exam‐
ple, if ibase is 16 and bc(1) is given the number string FFeA, the re‐
sulting decimal number will be 2550000000000, and if bc(1) is given the
number string 10e-4, the resulting decimal number will be 0.0016.
Accepting input as scientific notation is a non-portable extension.
Operators
The following arithmetic and logical operators can be used. They are
listed in order of decreasing precedence. Operators in the same group
have the same precedence.
++ -- Type: Prefix and Postfix
Associativity: None
Description: increment, decrement
- ! Type: Prefix
Associativity: None
Description: negation, boolean not
$ Type: Postfix
Associativity: None
Description: truncation
@ Type: Binary
Associativity: Right
Description: set precision
^ Type: Binary
Associativity: Right
Description: power
* / % Type: Binary
Associativity: Left
Description: multiply, divide, modulus
+ - Type: Binary
Associativity: Left
Description: add, subtract
<< >> Type: Binary
Associativity: Left
Description: shift left, shift right
= <<= >>= += -= *= /= %= ^= @=
Type: Binary
Associativity: Right
Description: assignment
== <= >= != < >
Type: Binary
Associativity: Left
Description: relational
&& Type: Binary
Associativity: Left
Description: boolean and
|| Type: Binary
Associativity: Left
Description: boolean or
The operators will be described in more detail below.
++ -- The prefix and postfix increment and decrement operators behave
exactly like they would in C. They require a named expression
(see the Named Expressions subsection) as an operand.
The prefix versions of these operators are more efficient; use
them where possible.
- The negation operator returns 0 if a user attempts to negate any
expression with the value 0. Otherwise, a copy of the expres‐
sion with its sign flipped is returned.
! The boolean not operator returns 1 if the expression is 0, or 0
otherwise.
Warning: This operator has a different precedence than the
equivalent operator in GNU bc(1) and other bc(1) implementa‐
tions!
This is a non-portable extension.
$ The truncation operator returns a copy of the given expression
with all of its scale removed.
This is a non-portable extension.
@ The set precision operator takes two expressions and returns a
copy of the first with its scale equal to the value of the sec‐
ond expression. That could either mean that the number is re‐
turned without change (if the scale of the first expression
matches the value of the second expression), extended (if it is
less), or truncated (if it is more).
The second expression must be an integer (no scale) and non-neg‐
ative.
This is a non-portable extension.
^ The power operator (not the exclusive or operator, as it would
be in C) takes two expressions and raises the first to the power
of the value of the second. The scale of the result is equal to
scale.
The second expression must be an integer (no scale), and if it
is negative, the first value must be non-zero.
* The multiply operator takes two expressions, multiplies them,
and returns the product. If a is the scale of the first expres‐
sion and b is the scale of the second expression, the scale of
the result is equal to min(a+b,max(scale,a,b)) where min() and
max() return the obvious values.
/ The divide operator takes two expressions, divides them, and re‐
turns the quotient. The scale of the result shall be the value
of scale.
The second expression must be non-zero.
% The modulus operator takes two expressions, a and b, and evalu‐
ates them by 1) Computing a/b to current scale and 2) Using the
result of step 1 to calculate a-(a/b)*b to scale
max(scale+scale(b),scale(a)).
The second expression must be non-zero.
+ The add operator takes two expressions, a and b, and returns the
sum, with a scale equal to the max of the scales of a and b.
- The subtract operator takes two expressions, a and b, and re‐
turns the difference, with a scale equal to the max of the
scales of a and b.
<< The left shift operator takes two expressions, a and b, and re‐
turns a copy of the value of a with its decimal point moved b
places to the right.
The second expression must be an integer (no scale) and non-neg‐
ative.
This is a non-portable extension.
>> The right shift operator takes two expressions, a and b, and re‐
turns a copy of the value of a with its decimal point moved b
places to the left.
The second expression must be an integer (no scale) and non-neg‐
ative.
This is a non-portable extension.
= <<= >>= += -= *= /= %= ^= @=
The assignment operators take two expressions, a and b where a
is a named expression (see the Named Expressions subsection).
For =, b is copied and the result is assigned to a. For all
others, a and b are applied as operands to the corresponding
arithmetic operator and the result is assigned to a.
The assignment operators that correspond to operators that are
extensions are themselves non-portable extensions.
== <= >= != < >
The relational operators compare two expressions, a and b, and
if the relation holds, according to C language semantics, the
result is 1. Otherwise, it is 0.
Note that unlike in C, these operators have a lower precedence
than the assignment operators, which means that a=b>c is inter‐
preted as (a=b)>c.
Also, unlike the standard (see the STANDARDS section) requires,
these operators can appear anywhere any other expressions can be
used. This allowance is a non-portable extension.
&& The boolean and operator takes two expressions and returns 1 if
both expressions are non-zero, 0 otherwise.
This is not a short-circuit operator.
This is a non-portable extension.
|| The boolean or operator takes two expressions and returns 1 if
one of the expressions is non-zero, 0 otherwise.
This is not a short-circuit operator.
This is a non-portable extension.
Statements
The following items are statements:
1. E
2. { S ; ... ; S }
3. if ( E ) S
4. if ( E ) S else S
5. while ( E ) S
6. for ( E ; E ; E ) S
7. An empty statement
8. break
9. continue
10. quit
11. halt
12. limits
13. A string of characters, enclosed in double quotes
14. print E , ... , E
15. stream E , ... , E
16. I(), I(E), I(E, E), and so on, where I is an identifier for a void
function (see the Void Functions subsection of the FUNCTIONS sec‐
tion). The E argument(s) may also be arrays of the form I[], which
will automatically be turned into array references (see the Array
References subsection of the FUNCTIONS section) if the correspond‐
ing parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are non-portable extensions.
Also, as a non-portable extension, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expres‐
sion) is omitted, it is assumed to be a constant 1.
The break statement causes a loop to stop iterating and resume execu‐
tion immediately following a loop. This is only allowed in loops.
The continue statement causes a loop iteration to stop early and re‐
turns to the start of the loop, including testing the loop condition.
This is only allowed in loops.
The if else statement does the same thing as in C.
The quit statement causes bc(1) to quit, even if it is on a branch that
will not be executed (it is a compile-time command).
Warning: The behavior of this bc(1) on quit is slightly different from
other bc(1) implementations. Other bc(1) implementations will exit as
soon as they finish parsing the line that a quit command is on. This
bc(1) will execute any completed and executable statements that occur
before the quit statement before exiting.
In other words, for the bc(1) code below:
for (i = 0; i < 3; ++i) i; quit
Other bc(1) implementations will print nothing, and this bc(1) will
print 0, 1, and 2 on successive lines before exiting.
The halt statement causes bc(1) to quit, if it is executed. (Unlike
quit if it is on a branch of an if statement that is not executed,
bc(1) does not quit.)
The limits statement prints the limits that this bc(1) is subject to.
This is like the quit statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a new‐
line.
Both scientific notation and engineering notation are available for
printing the results of expressions. Scientific notation is activated
by assigning 0 to obase, and engineering notation is activated by as‐
signing 1 to obase. To deactivate them, just assign a different value
to obase.
Scientific notation and engineering notation are disabled if bc(1) is
run with either the -s or -w command-line options (or equivalents).
Printing numbers in scientific notation and/or engineering notation is
a non-portable extension.
Strings
If strings appear as a statement by themselves, they are printed with‐
out a trailing newline.
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements. They can also be passed
to functions in variable parameters.
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the RESET section).
Assigning strings to variables and array elements and passing them to
functions are non-portable extensions.
Print Statement
The “expressions” in a print statement may also be strings. If they
are, there are backslash escape sequences that are interpreted spe‐
cially. What those sequences are, and what they cause to be printed,
are shown below:
\a: \a
\b: \b
\\: \
\e: \
\f: \f
\n: \n
\q: “
\r: \r
\t: \t
Any other character following a backslash causes the backslash and
character to be printed as-is.
Any non-string expression in a print statement shall be assigned to
last, like any other expression that is printed.
Stream Statement
The expressions in a stream statement may also be strings.
If a stream statement is given a string, it prints the string as though
the string had appeared as its own statement. In other words, the
stream statement prints strings normally, without a newline.
If a stream statement is given a number, a copy of it is truncated and
its absolute value is calculated. The result is then printed as though
obase is 256 and each digit is interpreted as an 8-bit ASCII character,
making it a byte stream.
Order of Evaluation
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations. This means, for example,
assuming that i is equal to 0, in the expression
a[i++] = i++
the first (or 0th) element of a is set to 1, and i is equal to 2 at the
end of the expression.
This includes function arguments. Thus, assuming i is equal to 0, this
means that in the expression
x(i++, i++)
the first argument passed to x() is 0, and the second argument is 1,
while i is equal to 2 before the function starts executing.
FUNCTIONS
Function definitions are as follows:
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
Any I in the parameter list or auto list may be replaced with I[] to
make a parameter or auto var an array, and any I in the parameter list
may be replaced with *I[] to make a parameter an array reference.
Callers of functions that take array references should not put an as‐
terisk in the call; they must be called with just I[] like normal array
parameters and will be automatically converted into references.
As a non-portable extension, the opening brace of a define statement
may appear on the next line.
As a non-portable extension, the return statement may also be in one of
the following forms:
1. return
2. return ( )
3. return E
The first two, or not specifying a return statement, is equivalent to
return (0), unless the function is a void function (see the Void Func‐
tions subsection below).
Void Functions
Functions can also be void functions, defined as follows:
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
They can only be used as standalone expressions, where such an expres‐
sion would be printed alone, except in a print statement.
Void functions can only use the first two return statements listed
above. They can also omit the return statement entirely.
The word “void” is not treated as a keyword; it is still possible to
have variables, arrays, and functions named void. The word “void” is
only treated specially right after the define keyword.
This is a non-portable extension.
Array References
For any array in the parameter list, if the array is declared in the
form
*I[]
it is a reference. Any changes to the array in the function are re‐
flected, when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a non-portable extension.
LIBRARY
All of the functions below, including the functions in the extended
math library (see the Extended Library subsection below), are available
when the -l or --mathlib command-line flags are given, except that the
extended math library is not available when the -s option, the -w op‐
tion, or equivalents are given.
Standard Library
The standard (see the STANDARDS section) defines the following func‐
tions for the math library:
s(x) Returns the sine of x, which is assumed to be in radians.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
c(x) Returns the cosine of x, which is assumed to be in radians.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
a(x) Returns the arctangent of x, in radians.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
l(x) Returns the natural logarithm of x.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
e(x) Returns the mathematical constant e raised to the power of x.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
j(x, n)
Returns the bessel integer order n (truncated) of x.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
Extended Library
The extended library is not loaded when the -s/--standard or -w/--warn
options are given since they are not part of the library defined by the
standard (see the STANDARDS section).
The extended library is a non-portable extension.
p(x, y)
Calculates x to the power of y, even if y is not an integer, and
returns the result to the current scale.
It is an error if y is negative and x is 0.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
r(x, p)
Returns x rounded to p decimal places according to the rounding
mode round half away from 0
(https://en.wikipedia.org/wiki/Round‐
ing#Round_half_away_from_zero).
ceil(x, p)
Returns x rounded to p decimal places according to the rounding
mode round away from 0 (https://en.wikipedia.org/wiki/Round‐
ing#Rounding_away_from_zero).
f(x) Returns the factorial of the truncated absolute value of x.
max(a, b)
Returns a if a is greater than b; otherwise, returns b.
min(a, b)
Returns a if a is less than b; otherwise, returns b.
perm(n, k)
Returns the permutation of the truncated absolute value of n of
the truncated absolute value of k, if k <= n. If not, it re‐
turns 0.
comb(n, k)
Returns the combination of the truncated absolute value of n of
the truncated absolute value of k, if k <= n. If not, it re‐
turns 0.
fib(n) Returns the Fibonacci number of the truncated absolute value of
n.
l2(x) Returns the logarithm base 2 of x.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
l10(x) Returns the logarithm base 10 of x.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
log(x, b)
Returns the logarithm base b of x.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
cbrt(x)
Returns the cube root of x.
root(x, n)
Calculates the truncated value of n, r, and returns the rth root
of x to the current scale.
If r is 0 or negative, this raises an error and causes bc(1) to
reset (see the RESET section). It also raises an error and
causes bc(1) to reset if r is even and x is negative.
gcd(a, b)
Returns the greatest common divisor (factor) of the truncated
absolute value of a and the truncated absolute value of b.
lcm(a, b)
Returns the least common multiple of the truncated absolute
value of a and the truncated absolute value of b.
pi(p) Returns pi to p decimal places.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
t(x) Returns the tangent of x, which is assumed to be in radians.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
a2(y, x)
Returns the arctangent of y/x, in radians. If both y and x are
equal to 0, it raises an error and causes bc(1) to reset (see
the RESET section). Otherwise, if x is greater than 0, it re‐
turns a(y/x). If x is less than 0, and y is greater than or
equal to 0, it returns a(y/x)+pi. If x is less than 0, and y is
less than 0, it returns a(y/x)-pi. If x is equal to 0, and y is
greater than 0, it returns pi/2. If x is equal to 0, and y is
less than 0, it returns -pi/2.
This function is the same as the atan2() function in many pro‐
gramming languages.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
sin(x) Returns the sine of x, which is assumed to be in radians.
This is an alias of s(x).
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
cos(x) Returns the cosine of x, which is assumed to be in radians.
This is an alias of c(x).
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
tan(x) Returns the tangent of x, which is assumed to be in radians.
If x is equal to 1 or -1, this raises an error and causes bc(1)
to reset (see the RESET section).
This is an alias of t(x).
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
atan(x)
Returns the arctangent of x, in radians.
This is an alias of a(x).
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
atan2(y, x)
Returns the arctangent of y/x, in radians. If both y and x are
equal to 0, it raises an error and causes bc(1) to reset (see
the RESET section). Otherwise, if x is greater than 0, it re‐
turns a(y/x). If x is less than 0, and y is greater than or
equal to 0, it returns a(y/x)+pi. If x is less than 0, and y is
less than 0, it returns a(y/x)-pi. If x is equal to 0, and y is
greater than 0, it returns pi/2. If x is equal to 0, and y is
less than 0, it returns -pi/2.
This function is the same as the atan2() function in many pro‐
gramming languages.
This is an alias of a2(y, x).
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
r2d(x) Converts x from radians to degrees and returns the result.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
d2r(x) Converts x from degrees to radians and returns the result.
This is a transcendental function (see the Transcendental Func‐
tions subsection below).
frand(p)
Generates a pseudo-random number between 0 (inclusive) and 1
(exclusive) with the number of decimal digits after the decimal
point equal to the truncated absolute value of p. If p is not
0, then calling this function will change the value of seed. If
p is 0, then 0 is returned, and seed is not changed.
ifrand(i, p)
Generates a pseudo-random number that is between 0 (inclusive)
and the truncated absolute value of i (exclusive) with the num‐
ber of decimal digits after the decimal point equal to the trun‐
cated absolute value of p. If the absolute value of i is
greater than or equal to 2, and p is not 0, then calling this
function will change the value of seed; otherwise, 0 is re‐
turned, and seed is not changed.
i2rand(a, b)
Takes the truncated value of a and b and uses them as inclusive
bounds to enerate a pseudo-random integer. If the difference of
the truncated values of a and b is 0, then the truncated value
is returned, and seed is not changed. Otherwise, this function
will change the value of seed.
srand(x)
Returns x with its sign flipped with probability 0.5. In other
words, it randomizes the sign of x.
brand()
Returns a random boolean value (either 0 or 1).
band(a, b)
Takes the truncated absolute value of both a and b and calcu‐
lates and returns the result of the bitwise and operation be‐
tween them.
If you want to use signed two’s complement arguments, use s2u(x)
to convert.
bor(a, b)
Takes the truncated absolute value of both a and b and calcu‐
lates and returns the result of the bitwise or operation between
them.
If you want to use signed two’s complement arguments, use s2u(x)
to convert.
bxor(a, b)
Takes the truncated absolute value of both a and b and calcu‐
lates and returns the result of the bitwise xor operation be‐
tween them.
If you want to use signed two’s complement arguments, use s2u(x)
to convert.
bshl(a, b)
Takes the truncated absolute value of both a and b and calcu‐
lates and returns the result of a bit-shifted left by b places.
If you want to use signed two’s complement arguments, use s2u(x)
to convert.
bshr(a, b)
Takes the truncated absolute value of both a and b and calcu‐
lates and returns the truncated result of a bit-shifted right by
b places.
If you want to use signed two’s complement arguments, use s2u(x)
to convert.
bnotn(x, n)
Takes the truncated absolute value of x and does a bitwise not
as though it has the same number of bytes as the truncated abso‐
lute value of n.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bnot8(x)
Does a bitwise not of the truncated absolute value of x as
though it has 8 binary digits (1 unsigned byte).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bnot16(x)
Does a bitwise not of the truncated absolute value of x as
though it has 16 binary digits (2 unsigned bytes).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bnot32(x)
Does a bitwise not of the truncated absolute value of x as
though it has 32 binary digits (4 unsigned bytes).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bnot64(x)
Does a bitwise not of the truncated absolute value of x as
though it has 64 binary digits (8 unsigned bytes).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bnot(x)
Does a bitwise not of the truncated absolute value of x as
though it has the minimum number of power of two unsigned bytes.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brevn(x, n)
Runs a bit reversal on the truncated absolute value of x as
though it has the same number of 8-bit bytes as the truncated
absolute value of n.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brev8(x)
Runs a bit reversal on the truncated absolute value of x as
though it has 8 binary digits (1 unsigned byte).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brev16(x)
Runs a bit reversal on the truncated absolute value of x as
though it has 16 binary digits (2 unsigned bytes).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brev32(x)
Runs a bit reversal on the truncated absolute value of x as
though it has 32 binary digits (4 unsigned bytes).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brev64(x)
Runs a bit reversal on the truncated absolute value of x as
though it has 64 binary digits (8 unsigned bytes).
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brev(x)
Runs a bit reversal on the truncated absolute value of x as
though it has the minimum number of power of two unsigned bytes.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
broln(x, p, n)
Does a left bitwise rotatation of the truncated absolute value
of x, as though it has the same number of unsigned 8-bit bytes
as the truncated absolute value of n, by the number of places
equal to the truncated absolute value of p modded by the 2 to
the power of the number of binary digits in n 8-bit bytes.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brol8(x, p)
Does a left bitwise rotatation of the truncated absolute value
of x, as though it has 8 binary digits (1 unsigned byte), by the
number of places equal to the truncated absolute value of p mod‐
ded by 2 to the power of 8.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brol16(x, p)
Does a left bitwise rotatation of the truncated absolute value
of x, as though it has 16 binary digits (2 unsigned bytes), by
the number of places equal to the truncated absolute value of p
modded by 2 to the power of 16.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brol32(x, p)
Does a left bitwise rotatation of the truncated absolute value
of x, as though it has 32 binary digits (4 unsigned bytes), by
the number of places equal to the truncated absolute value of p
modded by 2 to the power of 32.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brol64(x, p)
Does a left bitwise rotatation of the truncated absolute value
of x, as though it has 64 binary digits (8 unsigned bytes), by
the number of places equal to the truncated absolute value of p
modded by 2 to the power of 64.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brol(x, p)
Does a left bitwise rotatation of the truncated absolute value
of x, as though it has the minimum number of power of two un‐
signed 8-bit bytes, by the number of places equal to the trun‐
cated absolute value of p modded by 2 to the power of the number
of binary digits in the minimum number of 8-bit bytes.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
brorn(x, p, n)
Does a right bitwise rotatation of the truncated absolute value
of x, as though it has the same number of unsigned 8-bit bytes
as the truncated absolute value of n, by the number of places
equal to the truncated absolute value of p modded by the 2 to
the power of the number of binary digits in n 8-bit bytes.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bror8(x, p)
Does a right bitwise rotatation of the truncated absolute value
of x, as though it has 8 binary digits (1 unsigned byte), by the
number of places equal to the truncated absolute value of p mod‐
ded by 2 to the power of 8.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bror16(x, p)
Does a right bitwise rotatation of the truncated absolute value
of x, as though it has 16 binary digits (2 unsigned bytes), by
the number of places equal to the truncated absolute value of p
modded by 2 to the power of 16.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bror32(x, p)
Does a right bitwise rotatation of the truncated absolute value
of x, as though it has 32 binary digits (2 unsigned bytes), by
the number of places equal to the truncated absolute value of p
modded by 2 to the power of 32.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bror64(x, p)
Does a right bitwise rotatation of the truncated absolute value
of x, as though it has 64 binary digits (2 unsigned bytes), by
the number of places equal to the truncated absolute value of p
modded by 2 to the power of 64.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bror(x, p)
Does a right bitwise rotatation of the truncated absolute value
of x, as though it has the minimum number of power of two un‐
signed 8-bit bytes, by the number of places equal to the trun‐
cated absolute value of p modded by 2 to the power of the number
of binary digits in the minimum number of 8-bit bytes.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bmodn(x, n)
Returns the modulus of the truncated absolute value of x by 2 to
the power of the multiplication of the truncated absolute value
of n and 8.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bmod8(x, n)
Returns the modulus of the truncated absolute value of x by 2 to
the power of 8.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bmod16(x, n)
Returns the modulus of the truncated absolute value of x by 2 to
the power of 16.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bmod32(x, n)
Returns the modulus of the truncated absolute value of x by 2 to
the power of 32.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bmod64(x, n)
Returns the modulus of the truncated absolute value of x by 2 to
the power of 64.
If you want to a use signed two’s complement argument, use
s2u(x) to convert.
bunrev(t)
Assumes t is a bitwise-reversed number with an extra set bit one
place more significant than the real most significant bit (which
was the least significant bit in the original number). This
number is reversed and returned without the extra set bit.
This function is used to implement other bitwise functions; it
is not meant to be used by users, but it can be.
plz(x) If x is not equal to 0 and greater that -1 and less than 1, it
is printed with a leading zero, regardless of the use of the -z
option (see the OPTIONS section) and without a trailing newline.
Otherwise, x is printed normally, without a trailing newline.
plznl(x)
If x is not equal to 0 and greater that -1 and less than 1, it
is printed with a leading zero, regardless of the use of the -z
option (see the OPTIONS section) and with a trailing newline.
Otherwise, x is printed normally, with a trailing newline.
pnlz(x)
If x is not equal to 0 and greater that -1 and less than 1, it
is printed without a leading zero, regardless of the use of the
-z option (see the OPTIONS section) and without a trailing new‐
line.
Otherwise, x is printed normally, without a trailing newline.
pnlznl(x)
If x is not equal to 0 and greater that -1 and less than 1, it
is printed without a leading zero, regardless of the use of the
-z option (see the OPTIONS section) and with a trailing newline.
Otherwise, x is printed normally, with a trailing newline.
ubytes(x)
Returns the numbers of unsigned integer bytes required to hold
the truncated absolute value of x.
sbytes(x)
Returns the numbers of signed, two’s-complement integer bytes
required to hold the truncated value of x.
s2u(x) Returns x if it is non-negative. If it is negative, then it
calculates what x would be as a 2’s-complement signed integer
and returns the non-negative integer that would have the same
representation in binary.
s2un(x,n)
Returns x if it is non-negative. If it is negative, then it
calculates what x would be as a 2’s-complement signed integer
with n bytes and returns the non-negative integer that would
have the same representation in binary. If x cannot fit into n
2’s-complement signed bytes, it is truncated to fit.
hex(x) Outputs the hexadecimal (base 16) representation of x.
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
binary(x)
Outputs the binary (base 2) representation of x.
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
output(x, b)
Outputs the base b representation of x.
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
uint(x)
Outputs the representation, in binary and hexadecimal, of x as
an unsigned integer in as few power of two bytes as possible.
Both outputs are split into bytes separated by spaces.
If x is not an integer or is negative, an error message is
printed instead, but bc(1) is not reset (see the RESET section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
int(x) Outputs the representation, in binary and hexadecimal, of x as a
signed, two’s-complement integer in as few power of two bytes as
possible. Both outputs are split into bytes separated by spa‐
ces.
If x is not an integer, an error message is printed instead, but
bc(1) is not reset (see the RESET section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
uintn(x, n)
Outputs the representation, in binary and hexadecimal, of x as
an unsigned integer in n bytes. Both outputs are split into
bytes separated by spaces.
If x is not an integer, is negative, or cannot fit into n bytes,
an error message is printed instead, but bc(1) is not reset (see
the RESET section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
intn(x, n)
Outputs the representation, in binary and hexadecimal, of x as a
signed, two’s-complement integer in n bytes. Both outputs are
split into bytes separated by spaces.
If x is not an integer or cannot fit into n bytes, an error mes‐
sage is printed instead, but bc(1) is not reset (see the RESET
section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
uint8(x)
Outputs the representation, in binary and hexadecimal, of x as
an unsigned integer in 1 byte. Both outputs are split into
bytes separated by spaces.
If x is not an integer, is negative, or cannot fit into 1 byte,
an error message is printed instead, but bc(1) is not reset (see
the RESET section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
int8(x)
Outputs the representation, in binary and hexadecimal, of x as a
signed, two’s-complement integer in 1 byte. Both outputs are
split into bytes separated by spaces.
If x is not an integer or cannot fit into 1 byte, an error mes‐
sage is printed instead, but bc(1) is not reset (see the RESET
section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
uint16(x)
Outputs the representation, in binary and hexadecimal, of x as
an unsigned integer in 2 bytes. Both outputs are split into
bytes separated by spaces.
If x is not an integer, is negative, or cannot fit into 2 bytes,
an error message is printed instead, but bc(1) is not reset (see
the RESET section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
int16(x)
Outputs the representation, in binary and hexadecimal, of x as a
signed, two’s-complement integer in 2 bytes. Both outputs are
split into bytes separated by spaces.
If x is not an integer or cannot fit into 2 bytes, an error mes‐
sage is printed instead, but bc(1) is not reset (see the RESET
section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
uint32(x)
Outputs the representation, in binary and hexadecimal, of x as
an unsigned integer in 4 bytes. Both outputs are split into
bytes separated by spaces.
If x is not an integer, is negative, or cannot fit into 4 bytes,
an error message is printed instead, but bc(1) is not reset (see
the RESET section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
int32(x)
Outputs the representation, in binary and hexadecimal, of x as a
signed, two’s-complement integer in 4 bytes. Both outputs are
split into bytes separated by spaces.
If x is not an integer or cannot fit into 4 bytes, an error mes‐
sage is printed instead, but bc(1) is not reset (see the RESET
section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
uint64(x)
Outputs the representation, in binary and hexadecimal, of x as
an unsigned integer in 8 bytes. Both outputs are split into
bytes separated by spaces.
If x is not an integer, is negative, or cannot fit into 8 bytes,
an error message is printed instead, but bc(1) is not reset (see
the RESET section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
int64(x)
Outputs the representation, in binary and hexadecimal, of x as a
signed, two’s-complement integer in 8 bytes. Both outputs are
split into bytes separated by spaces.
If x is not an integer or cannot fit into 8 bytes, an error mes‐
sage is printed instead, but bc(1) is not reset (see the RESET
section).
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
hex_uint(x, n)
Outputs the representation of the truncated absolute value of x
as an unsigned integer in hexadecimal using n bytes. Not all of
the value will be output if n is too small.
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
binary_uint(x, n)
Outputs the representation of the truncated absolute value of x
as an unsigned integer in binary using n bytes. Not all of the
value will be output if n is too small.
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
output_uint(x, n)
Outputs the representation of the truncated absolute value of x
as an unsigned integer in the current obase (see the SYNTAX sec‐
tion) using n bytes. Not all of the value will be output if n
is too small.
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
output_byte(x, i)
Outputs byte i of the truncated absolute value of x, where 0 is
the least significant byte and number_of_bytes - 1 is the most
significant byte.
This is a void function (see the Void Functions subsection of
the FUNCTIONS section).
Transcendental Functions
All transcendental functions can return slightly inaccurate results, up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place). This
is unavoidable, and the article at https://people.eecs.berke‐
ley.edu/~wkahan/LOG10HAF.TXT explains why it is impossible and unneces‐
sary to calculate exact results for the transcendental functions.
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (scale) set to at least 1 higher than is
necessary. If exact results are absolutely required, users can double
the precision (scale) and then truncate.
The transcendental functions in the standard math library are:
• s(x)
• c(x)
• a(x)
• l(x)
• e(x)
• j(x, n)
The transcendental functions in the extended math library are:
• l2(x)
• l10(x)
• log(x, b)
• pi(p)
• t(x)
• a2(y, x)
• sin(x)
• cos(x)
• tan(x)
• atan(x)
• atan2(y, x)
• r2d(x)
• d2r(x)
RESET
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets. This means that several things happen.
First, any functions that are executing are stopped and popped off the
stack. The behavior is not unlike that of exceptions in programming
languages. Then the execution point is set so that any code waiting to
execute (after all functions returned) is skipped.
Thus, when bc(1) resets, it skips any remaining code waiting to be exe‐
cuted. Then, if it is interactive mode, and the error was not a fatal
error (see the EXIT STATUS section), it asks for more input; otherwise,
it exits with the appropriate return code.
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
PERFORMANCE
Most bc(1) implementations use char types to calculate the value of 1
decimal digit at a time, but that can be slow. This bc(1) does some‐
thing different.
It uses large integers to calculate more than 1 decimal digit at a
time. If built in a environment where BC_LONG_BIT (see the LIMITS sec‐
tion) is 64, then each integer has 9 decimal digits. If built in an
environment where BC_LONG_BIT is 32 then each integer has 4 decimal
digits. This value (the number of decimal digits per large integer) is
called BC_BASE_DIGS.
The actual values of BC_LONG_BIT and BC_BASE_DIGS can be queried with
the limits statement.
In addition, this bc(1) uses an even larger integer for overflow check‐
ing. This integer type depends on the value of BC_LONG_BIT, but is al‐
ways at least twice as large as the integer type used to store digits.
LIMITS
The following are the limits on bc(1):
BC_LONG_BIT
The number of bits in the long type in the environment where
bc(1) was built. This determines how many decimal digits can be
stored in a single large integer (see the PERFORMANCE section).
BC_BASE_DIGS
The number of decimal digits per large integer (see the PERFOR‐
MANCE section). Depends on BC_LONG_BIT.
BC_BASE_POW
The max decimal number that each large integer can store (see
BC_BASE_DIGS) plus 1. Depends on BC_BASE_DIGS.
BC_OVERFLOW_MAX
The max number that the overflow type (see the PERFORMANCE sec‐
tion) can hold. Depends on BC_LONG_BIT.
BC_BASE_MAX
The maximum output base. Set at BC_BASE_POW.
BC_DIM_MAX
The maximum size of arrays. Set at SIZE_MAX-1.
BC_SCALE_MAX
The maximum scale. Set at BC_OVERFLOW_MAX-1.
BC_STRING_MAX
The maximum length of strings. Set at BC_OVERFLOW_MAX-1.
BC_NAME_MAX
The maximum length of identifiers. Set at BC_OVERFLOW_MAX-1.
BC_NUM_MAX
The maximum length of a number (in decimal digits), which in‐
cludes digits after the decimal point. Set at BC_OVER‐
FLOW_MAX-1.
BC_RAND_MAX
The maximum integer (inclusive) returned by the rand() operand.
Set at 2^BC_LONG_BIT-1.
Exponent
The maximum allowable exponent (positive or negative). Set at
BC_OVERFLOW_MAX.
Number of vars
The maximum number of vars/arrays. Set at SIZE_MAX-1.
The actual values can be queried with the limits statement.
These limits are meant to be effectively non-existent; the limits are
so large (at least on 64-bit machines) that there should not be any
point at which they become a problem. In fact, memory should be ex‐
hausted before these limits should be hit.
ENVIRONMENT VARIABLES
As non-portable extensions, bc(1) recognizes the following environment
variables:
POSIXLY_CORRECT
If this variable exists (no matter the contents), bc(1) behaves
as if the -s option was given.
BC_ENV_ARGS
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line ar‐
guments. These are always processed first, so any files given
in BC_ENV_ARGS will be processed before arguments and files
given on the command-line. This gives the user the ability to
set up “standard” options and files to be used at every invoca‐
tion. The most useful thing for such files to contain would be
useful functions that the user might want every time bc(1) runs.
The code that parses BC_ENV_ARGS will correctly handle quoted
arguments, but it does not understand escape sequences. For ex‐
ample, the string “/home/gavin/some bc file.bc” will be cor‐
rectly parsed, but the string “/home/gavin/some "bc" file.bc”
will include the backslashes.
The quote parsing will handle either kind of quotes, ’ or “.
Thus, if you have a file with any number of single quotes in the
name, you can use double quotes as the outside quotes, as in
“some `bc' file.bc”, and vice versa if you have a file with dou‐
ble quotes. However, handling a file with both kinds of quotes
in BC_ENV_ARGS is not supported due to the complexity of the
parsing, though such files are still supported on the com‐
mand-line where the parsing is done by the shell.
BC_LINE_LENGTH
If this environment variable exists and contains an integer that
is greater than 1 and is less than UINT16_MAX (2^16-1), bc(1)
will output lines to that length, including the backslash (\).
The default line length is 70.
The special value of 0 will disable line length checking and
print numbers without regard to line length and without back‐
slashes and newlines.
BC_BANNER
If this environment variable exists and contains an integer,
then a non-zero value activates the copyright banner when bc(1)
is in interactive mode, while zero deactivates it.
If bc(1) is not in interactive mode (see the INTERACTIVE MODE
section), then this environment variable has no effect because
bc(1) does not print the banner when not in interactive mode.
This environment variable overrides the default, which can be
queried with the -h or --help options.
BC_SIGINT_RESET
If bc(1) is not in interactive mode (see the INTERACTIVE MODE
section), then this environment variable has no effect because
bc(1) exits on SIGINT when not in interactive mode.
However, when bc(1) is in interactive mode, then if this envi‐
ronment variable exists and contains an integer, a non-zero
value makes bc(1) reset on SIGINT, rather than exit, and zero
makes bc(1) exit. If this environment variable exists and is
not an integer, then bc(1) will exit on SIGINT.
This environment variable overrides the default, which can be
queried with the -h or --help options.
BC_TTY_MODE
If TTY mode is not available (see the TTY MODE section), then
this environment variable has no effect.
However, when TTY mode is available, then if this environment
variable exists and contains an integer, then a non-zero value
makes bc(1) use TTY mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be
queried with the -h or --help options.
BC_PROMPT
If TTY mode is not available (see the TTY MODE section), then
this environment variable has no effect.
However, when TTY mode is available, then if this environment
variable exists and contains an integer, a non-zero value makes
bc(1) use a prompt, and zero or a non-integer makes bc(1) not
use a prompt. If this environment variable does not exist and
BC_TTY_MODE does, then the value of the BC_TTY_MODE environment
variable is used.
This environment variable and the BC_TTY_MODE environment vari‐
able override the default, which can be queried with the -h or
--help options.
BC_EXPR_EXIT
If any expressions or expression files are given on the com‐
mand-line with -e, --expression, -f, or --file, then if this en‐
vironment variable exists and contains an integer, a non-zero
value makes bc(1) exit after executing the expressions and ex‐
pression files, and a zero value makes bc(1) not exit.
This environment variable overrides the default, which can be
queried with the -h or --help options.
BC_DIGIT_CLAMP
When parsing numbers and if this environment variable exists and
contains an integer, a non-zero value makes bc(1) clamp digits
that are greater than or equal to the current ibase so that all
such digits are considered equal to the ibase minus 1, and a
zero value disables such clamping so that those digits are al‐
ways equal to their value, which is multiplied by the power of
the ibase.
This never applies to single-digit numbers, as per the standard
(see the STANDARDS section).
This environment variable overrides the default, which can be
queried with the -h or --help options.
EXIT STATUS
bc(1) returns the following exit statuses:
0 No error.
1 A math error occurred. This follows standard practice of using
1 for expected errors, since math errors will happen in the
process of normal execution.
Math errors include divide by 0, taking the square root of a
negative number, using a negative number as a bound for the
pseudo-random number generator, attempting to convert a negative
number to a hardware integer, overflow when converting a number
to a hardware integer, overflow when calculating the size of a
number, and attempting to use a non-integer where an integer is
required.
Converting to a hardware integer happens for the second operand
of the power (^), places (@), left shift (<<), and right shift
(>>) operators and their corresponding assignment operators.
2 A parse error occurred.
Parse errors include unexpected EOF, using an invalid character,
failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an in‐
valid print statement, giving an invalid function definition,
attempting to assign to an expression that is not a named ex‐
pression (see the Named Expressions subsection of the SYNTAX
section), giving an invalid auto list, having a duplicate
auto/function parameter, failing to find the end of a code
block, attempting to return a value from a void function, at‐
tempting to use a variable as a reference, and using any exten‐
sions when the option -s or any equivalents were given.
3 A runtime error occurred.
Runtime errors include assigning an invalid number to any global
(ibase, obase, or scale), giving a bad expression to a read()
call, calling read() inside of a read() call, type errors, pass‐
ing the wrong number of arguments to functions, attempting to
call an undefined function, and attempting to use a void func‐
tion call as a value in an expression.
4 A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, fail‐
ing to open files, attempting to use files that do not have only
ASCII characters (bc(1) only accepts ASCII characters), attempt‐
ing to open a directory as a file, and giving invalid com‐
mand-line options.
The exit status 4 is special; when a fatal error occurs, bc(1) always
exits and returns 4, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interac‐
tive mode (see the INTERACTIVE MODE section), since bc(1) resets its
state (see the RESET section) and accepts more input when one of those
errors occurs in interactive mode. This is also the case when interac‐
tive mode is forced by the -i flag or --interactive option.
These exit statuses allow bc(1) to be used in shell scripting with er‐
ror checking, and its normal behavior can be forced by using the -i
flag or --interactive option.
INTERACTIVE MODE
Per the standard (see the STANDARDS section), bc(1) has an interactive
mode and a non-interactive mode. Interactive mode is turned on auto‐
matically when both stdin and stdout are hooked to a terminal, but the
-i flag and --interactive option can turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the RE‐
SET section), and in normal execution, flushes stdout as soon as execu‐
tion is done for the current input. bc(1) may also reset on SIGINT in‐
stead of exit, depending on the contents of, or default for, the
BC_SIGINT_RESET environment variable (see the ENVIRONMENT VARIABLES
section).
TTY MODE
If stdin, stdout, and stderr are all connected to a TTY, then “TTY
mode” is considered to be available, and thus, bc(1) can turn on TTY
mode, subject to some settings.
If there is the environment variable BC_TTY_MODE in the environment
(see the ENVIRONMENT VARIABLES section), then if that environment vari‐
able contains a non-zero integer, bc(1) will turn on TTY mode when
stdin, stdout, and stderr are all connected to a TTY. If the
BC_TTY_MODE environment variable exists but is not a non-zero integer,
then bc(1) will not turn TTY mode on.
If the environment variable BC_TTY_MODE does not exist, the default
setting is used. The default setting can be queried with the -h or
--help options.
TTY mode is different from interactive mode because interactive mode is
required in the bc(1) standard (see the STANDARDS section), and inter‐
active mode requires only stdin and stdout to be connected to a termi‐
nal.
Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that stdin,
stdout, and stderr are connected to a TTY and the BC_TTY_MODE environ‐
ment variable (see the ENVIRONMENT VARIABLES section) and its default
do not disable TTY mode. See the COMMAND LINE HISTORY section for more
information.
Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode
itself, it can be turned on or off with an environment variable:
BC_PROMPT (see the ENVIRONMENT VARIABLES section).
If the environment variable BC_PROMPT exists and is a non-zero integer,
then the prompt is turned on when stdin, stdout, and stderr are con‐
nected to a TTY and the -P and --no-prompt options were not used. The
read prompt will be turned on under the same conditions, except that
the -R and --no-read-prompt options must also not be used.
However, if BC_PROMPT does not exist, the prompt can be enabled or dis‐
abled with the BC_TTY_MODE environment variable, the -P and --no-prompt
options, and the -R and --no-read-prompt options. See the ENVIRONMENT
VARIABLES and OPTIONS sections for more details.
SIGNAL HANDLING
Sending a SIGINT will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the INTERACTIVE MODE section),
or the BC_SIGINT_RESET environment variable (see the ENVIRONMENT VARI‐
ABLES section), or its default, is either not an integer or it is zero,
bc(1) will exit.
However, if bc(1) is in interactive mode, and the BC_SIGINT_RESET or
its default is an integer and non-zero, then bc(1) will stop executing
the current input and reset (see the RESET section) upon receiving a
SIGINT.
Note that “current input” can mean one of two things. If bc(1) is pro‐
cessing input from stdin in interactive mode, it will ask for more in‐
put. If bc(1) is processing input from a file in interactive mode, it
will stop processing the file and start processing the next file, if
one exists, or ask for input from stdin if no other file exists.
This means that if a SIGINT is sent to bc(1) as it is executing a file,
it can seem as though bc(1) did not respond to the signal since it will
immediately start executing the next file. This is by design; most
files that users execute when interacting with bc(1) have function def‐
initions, which are quick to parse. If a file takes a long time to ex‐
ecute, there may be a bug in that file. The rest of the files could
still be executed without problem, allowing the user to continue.
SIGTERM and SIGQUIT cause bc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is SIGHUP; in
that case, and only when bc(1) is in TTY mode (see the TTY MODE sec‐
tion), a SIGHUP will cause bc(1) to clean up and exit.
COMMAND LINE HISTORY
bc(1) supports interactive command-line editing.
If bc(1) can be in TTY mode (see the TTY MODE section), history can be
enabled. This means that command-line history can only be enabled when
stdin, stdout, and stderr are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment
variable BC_TTY_MODE (see the ENVIRONMENT VARIABLES section).
If history is enabled, previous lines can be recalled and edited with
the arrow keys.
Note: tabs are converted to 8 spaces.
LOCALES
This bc(1) ships with support for adding error messages for different
locales and thus, supports LC_MESSAGES.
SEE ALSO
dc(1)
STANDARDS
bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017”) spec‐
ification at https://pubs.opengroup.org/onlinepubs/9699919799/utili‐
ties/bc.html . The flags -efghiqsvVw, all long options, and the exten‐
sions noted above are extensions to that specification.
In addition, the behavior of the quit implements an interpretation of
that specification that is different from all known implementations.
For more information see the Statements subsection of the SYNTAX sec‐
tion.
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (.) as a radix point, regardless of the value
of LC_NUMERIC.
This bc(1) supports error messages for different locales, and thus, it
supports LC_MESSAGES.
BUGS
Before version 6.1.0, this bc(1) had incorrect behavior for the quit
statement.
No other bugs are known. Report bugs at https://git.gavin‐
howard.com/gavin/bc .
AUTHORS
Gavin D. Howard ⟨gavin@gavinhoward.com⟩ and contributors.
Gavin D. Howard August 2024 BC(1)