10進数と2進数の変換表をtexで作りたい.
- 2進数は4桁
- 符号付きは2の補数表現
test.tex
\documentclass[a4paper]{jsarticle}
\usepackage{pgf} % pgfmath
\usepackage{pgffor} % foreach
\usepackage{multicol}
\begin{document}
\newcommand{\DtoB}[2][4]{% decimal to binary, unsigned
\pgfmathsetbasenumberlength{#1}% 4-digit default
\pgfmathbin{#2}\pgfmathresult%
}
\newcommand{\BtoD}[1]{% binary to decimal, unsigned
\pgfmathsetbasenumberlength{1}%
\pgfmathparse{0b#1}\pgfmathresult%
}
\newcommand{\DtoCB}[1]{% signed decimal to 4-digit binary
\ifnum #1 = 0%
\pgfmathsetbasenumberlength{4}%
\pgfmathbin{#1}\pgfmathresult%
\else%
\ifnum #1 > 0%
\pgfmathsetbasenumberlength{4}%
\pgfmathbin{#1}\pgfmathresult%
\else% #1 < 0
\pgfmathsetbasenumberlength{3}%
\pgfmathbin{8 + #1}1\pgfmathresult%
\fi%
\fi%
}
\newcommand{\CBtoD}[1]{% 4-digit binary to sgiend decimal -8, -7, ..., 6, 7
\pgfmathsetbasenumberlength{1}%
\pgfmathparse{0b#1}%
\ifnum \pgfmathresult > 7%
\pgfmathparse{-8 - (8 - 0b#1)}%
\pgfkeys{/pgf/number format/.cd,int trunc}%
\pgfmathprintnumber{\pgfmathresult}% convert -1.0 --> -1
\else%
\pgfmathparse{0b#1}\pgfmathresult%
\fi%
}
\def\DtoBloop#1{%
\foreach \x in {#1}{$(\x)_{10} = (\DtoB{\x})_2$\\}%
}
\def\DtoCBloop#1{%
\foreach \x in {#1}{$(\x)_{10} = (\DtoCB{\x})_2$\\}%
}
\def\BtoDloop#1{%
\foreach \x in {#1}{$(\BtoD{\x})_{10} = (\x)_2$\\}%
}
\def\CBtoDloop#1{%
\foreach \x in {#1}{$(\CBtoD{\x})_{10} = (\x)_2$\\}%
}
\begin{multicols*}{4}
\noindent
\DtoBloop{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
\columnbreak
\noindent
\DtoCBloop{-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7}
\columnbreak
\noindent
\CBtoDloop{0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111}
\columnbreak
\noindent
\BtoDloop{0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111}
\end{multicols*}
\end{document}
こうなります.