Efficient bitwise operations

Matthias Lang matthias@REDACTED
Mon Jun 23 09:53:36 CEST 2003

Rudolph van Graan writes:

 > I've had to write some bitwise operations yesterday, because I couldn't
 > locate any bifs or operations that do the same:

Bengt has already mentioned bsl/bsr. Also, writing

 > 	lroll1(<<B7:1,B6:1,B5:1,B4:1,B3:1,B2:1,B1:1,B0:1>>) ->
 > 	    <<B6:1,B5:1,B4:1,B3:1,B2:1,B1:1,B0:1,B7:1>>.

works, but is rather more verbose than

  lr(<<B7:1,Rest:7>>) ->
     <<Rest:7, B7:1>>.

the latter also generates shorter BEAM assembly (try the 'S' option
when you compile).

 > My question here has to do with the efficiency of the above code.
 > Normally, I would have used a single assembly instruction to achieve the
 > same result, but even though the code works, how efficient can it really
 > be? Are there any obvious things I've missed in the documentation?

The pragmatic approach is: if you are thinking about "how many
assembly instructions does this bit manipulation turn into", then it's
time to move the code to something more suited to the task, such as C
or assembler. Either that, or stop thinking about it ;-)

There are several ways of interfacing C code to Erlang, each with its
own convenience/performance tradeoffs. They're described at



More information about the erlang-questions mailing list