Rambling, thoughts and profundities on the subject of security and privacy in Web 2.0 and in particular Virtual Universes technologies. Occasionally I might diverge at bit.

2010/12/16

Reversing a binary object in Erlang

While parsing a file as binary data in Erlang, which is much more efficient than as a string, which is a list of integers, you need to reverse the accumulated string. For some reason there is no BIF, built-in function, in Erlang for that. Of course you could do something like:


1> list_to_binary(lists:reverse(binary_to_list(<<"abcd">>))).
<<"dcba">>

But that is wrong on all levels of wrong-ness. Instead, searching for a better solution, I found at trapexit.org ~ Erlang ~ fastest binary reverse a code snippet that looked as promising as it was puzzling. It proved to be slightly wrong, so here is the corrected version:

reverse(B) ->  S = size(B)*8,  <<X:S/integer-little>>=B, <<X:S/integer-big>>.

It works by taking the binary, reinterpreting it as a little-endian integer and then converting it to a big-endian integer, which reverses the bytes. I'm not sure how fast it is, but assume the endian functionality is written into Beam, so it should be as fast as it can be.

No comments: