并对两个二进制数进行操作

时间:2014-03-01 15:22:08

标签: matlab matlab-deployment matlab-compiler

我想对两个二进制数执行逻辑and操作。我尝试使用bitand,但该函数只能用于char数据类型。

我想对两个二进制数字执行and。 例如:

a=1101;
b=1010;

然后a and b的输出必须是

c=1000;

以下是我的尝试:

K=input('feed the value');
M=2^K;
S=input('feed the data');
disp(M);
s=dec2bin(S);
m=dec2bin(M-1);
q=bitand(s,m);
disp(q);

2 个答案:

答案 0 :(得分:1)

  

并且我有一个概念,即bitand仅适用于数据类型char

那是错的。 bitand需要整数输入参数。

示例:

>> K=9

K =

     8

>> L=12

L =

    12

>> bitand(K,L)

ans =

     8

答案 1 :(得分:1)

使用s将字符串s-'0'转换为二进制向量。对m执行相同操作。然后,您可以应用and (or &)

n = 4; %// specify number of bits
s = dec2bin(S,n)-'0';
m = dec2bin(M-1,n)-'0';
q = and(s,m); %// Or: q = s & m;

或使用de2bi(通讯工具箱),它直接将数字转换为二进制矢量:

n = 4; %// specify number of bits
s = de2bi(S,n,'left-msb');
m = de2bi(M-1,n,'left-msb');
q = and(s,m); %// Or: q = s & m;
相关问题