答案1
\overset
和的组合\substack
可让您将标签和箭头定位在相应数字上方。为确保标签的存在不会影响数字的间距,请使用\mathclap
。如果您有许多这样的情况,定义一个接受两个参数(标签和数字)的宏会很有用。
\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}
附录:上面的代码假设\bitpos
将在数学模式下使用。如果情况并非如此,只需提供一个\ensuremath{...}
包装器指令,即定义\bitpos
如下:
\newcommand\bitpos[2]{%
\ensuremath{\overset{\substack{\mathclap{\text{\tiny #1}}\\ \downarrow}}{#2}}}
答案2
可能比预期的要长一点,但是,嘿,您可以获得自动转换和可选的标签删除。
\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}