2

给定一个数字,例如 16877,我想测试一个位位置 (pos) 以查看是 0 还是 1。

例如,我知道上面的数字按数字表示为 100000111101101。

  • 位 1 = 1
  • 位 2 = 0
  • 位 3 = 1

考虑到数字应该已经作为二进制存储在 erlang 的 vm 中,我可以使用什么函数,比如:

Pos = 1,
Bit = getBit ( Pos , 16877 ).
4

3 回答 3

5

这个应该可以的。

bit(Number, Bit) ->
  (Number bsr Bit) band 1.
于 2013-03-01T19:56:24.633 回答
3

使用位运算符,卢克!

getBit(Pos, Number) ->
    case (1 bsl Pos) band Number of
        0 -> 0;
        _ -> 1
    end.

该函数接受从 0 开始的位置,但如果您喜欢基于 1 的索引,请随意减小 Pos:

1> Fun = fun(Pos, Num) -> case (1 bsl Pos) band Num of 0 -> 0; _ -> 1 end end.
#Fun<erl_eval.12.82930912>
2> Fun(0, 16877).
1
3> Fun(1, 16877).
0
4> Fun(2, 16877).
1
5> Fun(3, 16877).
1
于 2013-03-01T19:19:17.807 回答
-1

我不知道库中是否有类似的东西,但这里有一个实现:

get_bit(1, Num) -> Num rem 2;
get_bit(Pos, Num) -> get_bit(Pos-1, Num div 2).

和输出:

1> test:get_bit(2, 16877).
0
2> test:get_bit(3, 16877).
1
3> test:get_bit(6, 16877). 
1
4> test:get_bit(10, 16877).
0
5> test:get_bit(11, 16877).
0
于 2013-03-01T19:19:39.883 回答