Efficient bitwise operations

Chandrashekhar Mullaparthi Chandrashekhar.Mullaparthi@REDACTED
Fri Jun 20 11:52:15 CEST 2003


You can treat each byte as an integer and do

bsl - bit shift left
bsr - bit shift right

These operators are described in the first chapter of the red book.

11> 1 bsl 1.
2
12> 1 bsl 2.
4
13> 4 bsr 1.
2
14> 4 bsr 2.
1

To swap nibbles

swap(Int) ->
    ((Int band 15) bsl 4) + ((Int band 240) bsr 4).

cheers
Chandru

-----Original Message-----
From: Rudolph van Graan [mailto:rvg@REDACTED]
Sent: 20 June 2003 09:34
To: erlang-questions@REDACTED
Subject: Efficient bitwise operations


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



 NOTICE AND DISCLAIMER:
This email (including attachments) is confidential.  If you have received
this email in error please notify the sender immediately and delete this
email from your system without copying or disseminating it or placing any
reliance upon its contents.  We cannot accept liability for any breaches of
confidence arising through use of email.  Any opinions expressed in this
email (including attachments) are those of the author and do not necessarily
reflect our opinions.  We will not accept responsibility for any commitments
made by our employees outside the scope of our business.  We do not warrant
the accuracy or completeness of such information.




More information about the erlang-questions mailing list