# Efficient bitwise operations

Per Gustafsson <>
Sun Jun 22 22:51:14 CEST 2003

```There are better ways to implement rroll, lroll and swap

lroll(Byte, Rolls) ->
RestSize = 8-Rolls,
<<First:Rolls, Rest:RestSize>> = Byte
<<Rest:RestSize, First:Rolls>>.

rroll(Byte, Rolls) ->
FirstSize = 8-Rolls,
<<First:FirstSize, Rest:Rolls>> = Byte,
<<Rest:Rolls, First:FirstSize>>.

or

rroll(Byte, Rolls) ->
lroll(Byte, 8-Rolls).

swap(<<High:4, Low:4>>) ->
<<Low:4, High:4>>

Per

On Fri, 20 Jun 2003, Rudolph van Graan wrote:

> Hi there again,
>
> Thanks again for all the answers previously - helped me a lot!
>
> I've had to write some bitwise operations yesterday, because I couldn't
> locate any bifs or operations that do the same:
>
> Bitwise roll left:

>
> 	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>>.
>
> 	rroll(<<Byte>>,Rolls) when Rolls > 0 ->
> 	    Output = rroll1(<<Byte>>),
> 	    rroll(Output,Rolls-1);
>
> 	rroll(Byte,0) ->
> 	    Byte.
>
>
> Bitwise roll right:
>
> 	lroll(<<Byte>>,Rolls) when Rolls > 0 ->
> 	    Output = lroll1(<<Byte>>),
> 	    lroll(Output,Rolls-1);
>
> 	lroll(Byte,0) ->
>
> 	rroll1(<<B7:1,B6:1,B5:1,B4:1,B3:1,B2:1,B1:1,B0:1>>) ->
> 	    <<B0:1,B7:1,B6:1,B5:1,B4:1,B3:1,B2:1,B1:1>>.
>
> Bitwise high <-> low nibble swap:
>
> 	swap(<<B7:1,B6:1,B5:1,B4:1,B3:1,B2:1,B1:1,B0:1>>) ->
> 	    <<B3:1,B2:1,B1:1,B0:1,B7:1,B6:1,B5:1,B4:1>>.
>
> 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?
>
> Thanks again!
>
> Rudolph
>

```