简体   繁体   中英

How to get a bit of a decimal integer in erlang

Given a number, for example 16877, I want to test a bit position (pos) to see if 0 or 1.

For instance, I know that the above number is digit wise reppresented as 100000111101101.

  • bit pos 1 = 1
  • bit pos 2 = 0
  • bit pos 3 = 1

Considering numbers should be stored in erlang's vm as binary already, what function can I use to, say:

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

This ought to do it.

bit(Number, Bit) ->
  (Number bsr Bit) band 1.

Use bitwise operators, Luke!

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

The function accepts position from 0 but if you like 1-based indexes, feel free to decrease 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

I don't know if there is something like this in a library, but here is an implementation:

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

And the output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM