calculator.hpp is a header-only C++ library for parsing and
evaluating integer arithmetic expressions e.g. "10 * (7 - 1)". It compiles with any
C++ compiler and works with any integer type e.g. int,
long, uint64_t.
calculator is a simple but fast operator-precedence parser.
calculator.hpp uses the same operator precedence and associativity
as the C++ programming language and also supports the power operator.
| Operator | Description |
| | | Bitwise Inclusive OR |
| ^ | Bitwise Exclusive OR |
| & | Bitwise AND |
| ~ | Unary Complement |
| << | Shift Left |
| >> | Shift Right |
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulo |
| ** | Raise to power |
Functions defined in calculator.hpp.
int calculator::eval(const std::string& expression);
template <typename T>
T calculator::eval<T>(const std::string& expression);calculator::eval("1+2") takes a string with an integer arithmetic
expression as an argument, evaluates the arithmetic expression and returns
the result. If the expression string is not a valid integer arithmetic
expression a calculator::error exception is thrown.
#include "calculator.hpp"
#include <stdint.h>
#include <iostream>
int main()
{
try
{
int result = calculator::eval("(0 + ~(255 & 1000)*3) / -2");
std::cout << result << std::endl;
// 64-bit arithmetic
int64_t r64 = calculator::eval<int64_t>("2**60");
std::cout << r64 << std::endl;
}
catch (calculator::error& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}