Bit twiddling

Mark Scandariato <>
Thu Mar 31 19:26:52 CEST 2005


If you have a binary you could do something hideous like:

%%%%%%%%%%%%%%%%
-module(foo).
-export([twiddle/1]).

twiddle(Bin) when is_binary(Bin) ->
     Bits = 8 * size(Bin),
     twiddle(Bin, -1, Bits+1, 0, 0, Bits-1).

twiddle(_, _, _, 0, _, -1) -> none;
twiddle(_, H, L, C, _, -1) -> {H-1,L-1,C};
twiddle(Bin, H, L, C, Pre, Post) ->
     <<_:Pre, X:1, _:Post>> = Bin,
     {H1,L1} = hilo(X, H, L, Post+1),
     twiddle(Bin, H1, L1, C+X, Pre+1, Post-1).

hilo(0, H, L, _) -> {H, L};
hilo(1, H, L, C) -> {max(H,C), min(L,C)}.

min(A, B) when A < B -> A;
min(_, B) -> B.

max(A, B) when A > B -> A;
max(_, B) -> B.
%%%%%%%%%%%%%%%%

1> foo:twiddle(<<9876:16>>).
{13,2,6}
2>

Mark.

Joel Reymont wrote:
> Folks,
> 
> What's the most effective way to do bit twiddling in Erlang? 
> 
> Should I convert the int into a list of bits? How would I efficiently do this?
> 
> I'm looking to figure out the highest and lowest bit set in an integer as
> well as count the number of bits set.
> 
>     Thanks, Joel
> 



More information about the erlang-questions mailing list