hhh
hhh

Reputation: 52840

Bitwise commands such as Bitor with many inputs?

Matlab takes only two inputs with bitwise commands such as bitor. bitor(1,2) returns 3 and bitor(1,2,4) does not return 7 but:

ASSUMEDTYPE must be an integer type name.

Currently, I create for-loops to basically create a bitwise command to take as many inputs as needed. I feel the for-loops for this kind of thing is reinvention of the wheel.

Is there some easy way of creating the bitwise operations with many inputs?

Currently an example with some random numbers, must return 127

indices=[1,23,45,7,89,100];
indicesOR=0;
for term=1:length(indices)
    indicesOR=bitor(indicesOR,indices(term));
end

Upvotes: 5

Views: 852

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

If you don't mind getting strings involved (may be slow):

indicesOR  = bin2dec(char(double(any(dec2bin(indices)-'0'))+'0'));

This uses dec2bin to convert to strings of '0' and '1'; converts to numbers 0 and 1 by subtracting '0'; applys an "or" operation column-wise using any; and then converts back.

For AND (instead of OR): replace any by all:

indicesAND = bin2dec(char(double(all(dec2bin(indices)-'0'))+'0'));

For XOR: use rem(sum(...),2):

indicesXOR = bin2dec(char(double(rem(sum(dec2bin(indices)-'0'),2))+'0'))

EDIT: I just found out about functions de2bi and bi2de (Communications Toolbox), which avoid using strings. However, they seem to be slower!

indicesOR  = bi2de(double(any(de2bi(indices))));
indicesAND = bi2de(double(all(de2bi(indices))));
indicesXOR = bi2de(double(rem(sum((de2bi(indices))));

Another approach is to define a recursive function, exploiting the fact that AND, OR, XOR operations are (bit-wise) associative, that is, x OR y OR z equals (x OR y) OR z. The operation to be applied is passed as a function handle.

function r = bafun(v, f)
%BAFUN  Binary Associative Function
%   r = BAFUN(v,f)
%   v is a vector with at least two elements
%   f is a handle to a function that operates on two numbers

if numel(v) > 2
    r = bafun([f(v(1), v(2)) v(3:end)], f);
else
    r = f(v(1), v(2));
end

Example:

>> bafun([1,23,45,7,89,100], @bitor)
ans =
   127

Upvotes: 2

Related Questions