Math Mode – How to Illustrate Decimal to Binary Conversion in LaTeX

equationsmath-modetables

As part of my homework for discrete math I need to convert different decimal values, both positive and negative, to 8-bit binary representations using signed magnitude, 1's complement, and 2's complement. Could anyone suggest an elegant way to present my solutions?

An example of handwritten technique is available this

enter image description here

Best Answer

In your initial question I thought you were looking at suggestions for ways of tabulating the bit patterns, something like the first couple of examples. But your edit indicated you wanted to display the working. Something like this might work for that, I just do the easy unsigned case as you showed, I leave the rest as you say it's homework:-)

enter image description here

\documentclass{article}

\newcommand\decbin[9]{%
\par\smallskip
\makebox[3cm][r]{$#1$\ }\fbox{#2}\,\fbox{#3}\,\fbox{#4}\,\fbox{#5}\,\fbox{#6}\,\fbox{#7}\,\fbox{#8}\,\fbox{#9}\par}


\def\unsignedbytecalc#1{%
\par\smallskip
\noindent$#1_{10}$\par
\smallskip
\gdef\result{}%
$\left.\begin{array}{r@{\quad}|c}\udbc{#1}\end{array}\right\}\result$\par}

\makeatletter

\def\udbc#1{%
\ifnum#1=\z@
\expandafter\@gobble
\else
\expandafter\@firstofone
\fi
{2)\!\underline{\,#1}&\edef\r{\ifodd#1 1\else 0\fi}\r\xdef\result{\r\result}\\
\expandafter\udbc\expandafter{\the\numexpr(\ifodd#1 #1-1\else#1\fi)/2\relax}%
}}


\begin{document}

\decbin{13} 00001101
\decbin{54} 00110110

\unsignedbytecalc{156}

\end{document}