[Tex/LaTex] Binary arithmetic

math-mode

Is there a package to perform binary arithmetic like addition, subtraction, and so on? Ex: 1101 + 0001 = 1110.

BUT not as text, like I've typed in here!

Also, is there any other packager rather than xlop for decimal arithmetic operations?

Best Answer

The math functions built into pgf can be used:

enter image description here

Notes:

  • An integer with prefix 0b or 0B is interpreted as a binary number and is automatically converted to base 10. Hence the prefixes in 0b#1 + 0b#2. It should be noted that this feature of treating numbers with a leading 0 as an octal number can not be disabled as per Martin Scharrer's answer at Unexpected results from pgfmath functions with numbers with leading 0.

  • \pgfmathbin{x} converts an integer to a binary representation.

  • \pgfmathprintnumber is optional and is used to format the number. In this case it automatically detects that the decimal value of the addition is an integer and produces 102 instead of 102.0 as is the case for the first decimal addition.

Code:

\documentclass{article}
\usepackage{pgf}
\newcommand{\BinaryAdd}[2]{%
    {#1}_2 + {#2}_2 = \pgfmathbin{0b#1 + 0b#2}% compute binary addition
    \pgfmathresult_2% format output to make it clear it is base 2
}%
\newcommand{\BinarySub}[2]{%
    {#1}_2 - {#2}_2 = \pgfmathbin{0b#1 - 0b#2}% compute binary subtraction
    \pgfmathresult_2% format output to make it clear it is base 2
}%

\newcommand{\DecimalAdd}[2]{%
    #1 + #2 = \pgfmathparse{#1 + #2}%    compute addition
    \pgfmathprintnumber{\pgfmathresult}% format output
}%
\newcommand{\DecimalSub}[2]{%
    #1 - #2 = \pgfmathparse{#1 - #2}%    compute subtraction
    \pgfmathprintnumber{\pgfmathresult}% format output
}%
\begin{document}
$\BinaryAdd{101}{0001}$\par
$\BinarySub{101}{0001}$

\bigskip
$\DecimalAdd{101}{0001}$\par
$\DecimalSub{101}{0001}$
\end{document}
Related Question