Graphics in LaTeX for bits representation within boxes

Remarks

Using the almighty tikz I created a command \drawbits, which takes a comma separated list of values, where 0 denotes an unset bit and anything else (e.g. 1) a set bit.

Implementation

\documentclass{article}
\pagestyle{empty}%for cropping
\usepackage{tikz}
\newcommand\drawbits[1]{%
    \tikz[x=1.5ex,y=1.5ex,every path/.style={draw=black,semithick}]{%
        \foreach \y [count=\i] in {#1} {
            \expandafter\ifx\y0
                \draw (\i,0) rectangle (\i+1,1);
            \else
                \draw (\i,0) rectangle (\i+1,1);
                \filldraw[fill=black] (\i+0.2,0.2) rectangle (\i*1+0.8,0.8);
            \fi
        }%
    }%
}
\begin{document}
My bits: \drawbits{0,0,1,1,0,1,0}

\large My bits: \drawbits{0,0,1,1,0,1,0}

\Large My bits: \drawbits{0,0,1,1,0,1,0}

\LARGE My bits: \drawbits{0,0,1,1,0,1,0}
\end{document}

Output

enter image description here


As mentioned in comments, you should consider, bytefield package for such constructions. It offers many sophisticated layouts out of the box. For more details, type texdoc bytefield from the command line/prompt) or visit texdoc.net. An example (from th manual):

\documentclass{article}
\usepackage{bytefield}
\begin{document}
  \begin{bytefield}[endianness=little,bitwidth=0.11111\linewidth]{8}
%\bitheader{0-7} \\
\bitbox{1}{Res} & \bitbox{1}{BE} & \bitbox{1}{CF}
& \bitbox{3}{$\mbox{Name\_Len}-1$} & \bitbox{2}{Len\_Len} \\
\end{bytefield}
\end{document}

enter image description here

Tags:

Graphics