How to define MSB or LSB of a binary number
A combination of \overset
and \substack
lets you position the labels and the arrows above the respective digits. To assure that the presence of the labels doesn't affect the spacing of the digits, use \mathclap
. If you have many such cases, it's useful to define a macro that takes two arguments -- the label and the digit.
\documentclass{article}
\usepackage{mathtools} % to access \overset, \substack, \mathclap, and \text macros
\newcommand\bitpos[2]{%
\overset{\substack{\mathclap{\text{\tiny #1}}\\ \downarrow}}{#2}}
\begin{document}
$\bitpos{MSB}{1}001100\bitpos{LSB}{1}$
\end{document}
Addendum: The code shown above assumes that \bitpos
will be used in math mode. If that's not necessarily the case, just provide an \ensuremath{...}
wrapper instruction as well, i.e., define \bitpos
as follows:
\newcommand\bitpos[2]{%
\ensuremath{\overset{\substack{\mathclap{\text{\tiny #1}}\\ \downarrow}}{#2}}}
Perhaps a bit longer than expected, but, hey, you get automatic conversion and optional removal of the labels.
\documentclass{article}
\usepackage{amsmath,xparse}
\ExplSyntaxOn
\NewDocumentCommand{\bits}{O{}m}
{
\group_begin:
\keys_set:nn { chekooo/bits } { #1 }
\chekooo_bits:n { #2 }
\group_end:
}
\keys_define:nn { chekooo/bits }
{
convert .bool_set:N = \l_chekooo_convert_bool,
convert .initial:n = false,
convert .default:n = true,
nosb .bool_set:N = \l_chekooo_show_bool,
nosb .initial:n = false,
nosb .default:n = true,
}
\cs_new_protected:Nn \chekooo_bits:n
{
\bool_if:NTF \l_chekooo_convert_bool
{
\chekooo_process:f { \int_to_bin:n { #1 } }
}
{
\chekooo_process:n { #1 }
}
}
\cs_new_protected:Nn \chekooo_process:n
{
\bool_if:NTF \l_chekooo_show_bool
{
#1
}
{
\chekooo_bits_show:n { #1 }
}
}
\cs_generate_variant:Nn \chekooo_process:n { f }
\cs_new_protected:Nn \chekooo_bits_show:n
{
\int_compare:nTF { \tl_count:n { #1 } < 2 }
{
#1
}
{
\__chekooo_bits_show:n { #1 }
}
}
\cs_new_protected:Nn \__chekooo_bits_show:n
{
\seq_set_split:Nnn \l__chekooo_bits_seq { } { #1 }
\seq_pop_left:NN \l__chekooo_bits_seq \l__chekoo_msb_tl
\seq_pop_right:NN \l__chekooo_bits_seq \l__chekoo_lsb_tl
\mspace{10mu} % for the M
\overset
{
\substack{\scriptscriptstyle\hidewidth\mathrm{MSB}\hidewidth\\\downarrow}
}
{\l__chekoo_msb_tl}
\mspace{8mu}
\seq_use:Nn \l__chekooo_bits_seq { \mspace{8mu} }
\mspace{8mu}
\overset
{
\substack{\scriptscriptstyle\hidewidth\mathrm{LSB}\hidewidth\\\downarrow}
}
{\l__chekoo_lsb_tl}
\mspace{8mu}
}
\seq_new:N \l__chekooo_bits_seq
\tl_new:N \l__chekoo_msb_tl
\tl_new:N \l__chekoo_lsb_tl
\ExplSyntaxOff
\begin{document}
\[
\bits{1001}+
\bits[nosb]{1001}+
\bits[convert]{42}+
\bits[convert,nosb]{42}
\]
\[
\bits{0}+\bits{1}+\bits{10}+\bits{11}+\bits{100}
\]
\end{document}