bxor

Vladimir Sekissov <>
Wed Feb 19 05:57:31 CET 2003


Good day,

dan-erlang> I think initially I'd like to be able to XOR two binaries. Or two lists.
dan-erlang> What if the sizes of the two binaries differ? Will I need to pad one of
dan-erlang> them to the size of the other? Thanks much.

It depends from that you need. For example if your bytes are in
network order and you want to pad your binaries(lists):

do_bxor(B1, B2) when binary(B1), binary(B2) ->
  list_to_binary(do_bxor(binary_to_list(B1), binary_to_list(B2)));
do_bxor(L1, L2) when list(L1), list(L2) ->
  do_bxor(lists:reverse(L1), lists:reverse(L2), []).

do_bxor([], L2, Ret) ->
  lists:reverse(L2) ++ Ret;
do_bxor(L1, [], Ret) ->
  lists:reverse(L1) ++ Ret;
do_bxor([I1|Rest1], [I2|Rest2], Acc) ->
  do_bxor(Rest1, Rest2, [I1 bxor I2|Acc]).


()22> test:do_bxor([1, 1, 1], [5, 2 ,2, 2]).
[5,3,3,3]

()23> test:do_bxor(<<1, 1, 1>>, <<5, 2 ,2, 2>>).
<<5,3,3,3>>

()24> test:do_bxor(<<1, 1>>, <<2 ,2, 2>>).
<<2,3,3>>

Best Regards,
Vladimir Sekissov
	   
dan-erlang> Matthias Lang wrote:
dan-erlang> > 
dan-erlang> > Dan Melomedman writes:
dan-erlang> >  > Hi. I need to bxor other datatypes than integers. What's the
dan-erlang> >  > recommended way of doing something like this? Thanks.
dan-erlang> > 
dan-erlang> > It depends on what you want to do and how fast you want to do it and
dan-erlang> > how long you want to spend programming it. 
dan-erlang> 
dan-erlang> It doesn't need to be fast, and I don't want to spend too much time
dan-erlang> programming just to be able to XOR. So I am hoping there's an easy way.
dan-erlang> 
dan-erlang> > A simple byte-wise approach to XOR-ing the binary Bin with a constant is:
dan-erlang> > 
dan-erlang> >   list_to_binary( [X bxor 123 || X <- binary_to_list(Bin)] )
dan-erlang> 
dan-erlang> I think initially I'd like to be able to XOR two binaries. Or two lists.
dan-erlang> What if the sizes of the two binaries differ? Will I need to pad one of
dan-erlang> them to the size of the other? Thanks much.



More information about the erlang-questions mailing list