Jesper
Jesper

Reputation: 43

Matlab: How to use 'bitxor' for more inputs than 2?

I hope someone can help me with this particular problem:

I need to calculate 'bitxor' for more than two inputs. I have a vector of intputs/elements where the number of inputs/elements varies. For instance, in case of a four elements Vector, the solution is as follows:

Vector: Y = [1 3 5 7];

Solution: bitxor(bitxor(Y(1),Y(2)),bitxor(Y(3),Y(4)));

Is there any way where I can write this in a more general way, such that I get one value/elemet no matter how many inputs elements there is in vector Y?

Upvotes: 1

Views: 2058

Answers (3)

Mustafa Elec
Mustafa Elec

Reputation: 139

This is another solution , but it overwrites the original vector.

Y = [1, 3, 5, 7];

for i=1:length(Y)-1
    Y(i+1) = bitxor(Y(i),Y(i+1)); 
end
finalVal = Y(end)

Upvotes: 0

Ryan J. Smith
Ryan J. Smith

Reputation: 1140

A 'back of the envelope' solution seems to be to convert each number in the list to binary and sum up the number of 1s in each bit column.

If the sum in a particular column number is even, then that column will hold a 0 in your final (binary) result, if it is odd, it will hold a 1.

So your example of bitxor([1 3 5 7]):

0001 (dec 1)
0011 (dec 3)
0101 (dec 5)
0111 (dec 7)
====

Bit-wise sum: 0224 (Not base 2 here, obviously)

Convert via even/odd rule above:

0224 => bin 0000 (or dec 0)

I tried it on a few quick examples offhand and didn't run into an exception.

So some code to try the solution out:

Y = [1, 3, 5, 7];
strMat = dec2bin(Y); % Convert Y to char matrix of binary values

for i = 1:size(strMat,2)
    colSum = sum( str2num(strMat(:,i))); % Sum up each column
    finalVal(i) = num2str( mod(colSum,2)); % Check whether column sum is even
end

finalVal = bin2dec(finalVal); % Convert solution to decimal

Upvotes: 1

fpe
fpe

Reputation: 2750

The solution I will describe now is far from being optimal, but you can give it a try anyway:

Y1 = Y(1:2:end);
Y2 = Y(2:2:end);
arrayfun(@(i) bitxor(bitxor(Y1(i),Y2(i)),bitxor(Y1(i),Y2(i))),1:size(Y1,1))

Upvotes: 0

Related Questions