如何关联"标签"在Erlang位串中的每个位?

时间:2018-03-29 21:32:20

标签: erlang bits bitstring

假设我有以下bitstring:

B = <<0:5>>.

其中包含五位:<<0,0,0,0,0>>

要设置其中一个位,我使用此辅助函数:

-spec set(Bits :: bitstring(), BitIndex :: non_neg_integer()) -> bitstring().

set(Bits, BitIndex) ->
    << A:BitIndex/bits, _:1, B/bits >> = Bits,
    << A/bits, 1:1, B/bits >>.

我这样称呼函数:

B2 = bit_utils:set(B, 2). % Referring to a specific bit by its index (2).

这将给我这个比特串:<<0,0,1,0,0>>

是否有可能以某种方式关联&#34;标签&#34;位串中的每个位?

这样的事情:<<A1=0,A2=0,A3=1,A4=0,A5=0, … >>

因此我可以通过其标签来引用每个位,而不是像上面函数中那样引用它的索引。通过编写具有类似于此的签名的函数:set(Bits, BitLabel)

可以这样调用:set(Grid, "A3")

在我的应用程序中,我使用81位的固定大小的位串作为9 * 9&#34;网格&#34; (行和列)。能够参考每个&#34;细胞&#34;通过其行/列标识符(例如A3)将非常有用。

1 个答案:

答案 0 :(得分:2)

不,您无法将标签与位相关联。由于标签和索引之间的映射似乎在你的情况下是固定的,我改为创建另一个函数,将标签映射到它的索引,如下所示:

position(a1) -> 0;
position(a2) -> 1;
...

然后在set中使用它:

set(Bits, Label) ->
    BitIndex = position(Label),
    << A:BitIndex/bits, _:1, B/bits >> = Bits,
    << A/bits, 1:1, B/bits >>.

现在你可以用一个标签:

的原子来调用set/2
B2 = set(B, a1),
B3 = set(B2, c2).
相关问题