为什么代码显示错误?

Why code displays error?

你能帮我解释一下为什么这段代码会出错吗?我想使用 XOR,但我不能。我正在尝试使用以下公式来做到这一点:“A XOR B= (A AND ~B)OR(~A AND B)。你能提示我做错了什么吗?

public = 'public';
password = 'passwd';
if length(public)== length(password)
    public = uint8(public);
    password = uint8(password);
    negpublic = ~(dec2bin(public));
    negpassword = ~(dec2bin(password));
    score = bitor(bitand(public,negpassword),bitand(negpublic,password));
    public = dec2bin(public);
    password = char(password)


else
    fprintf('length not ok!\n' );
end

为什么代码会产生错误?

我们先列出错误:

Error using bitand Inputs must be signed or unsigned integers of the same class or scalar doubles.

Error in foo (line 8) score = bitor(bitand(public,negpassword),bitand(negpublic,password));

好的,所以下面一行会产生错误:

score = bitor(bitand(public,negpassword),bitand(negpublic,password)); 

我们可以将其分解并看到以下两个表达式自己都会产生错误

bitand(public,negpassword)
bitand(negpublic,password) 

为什么?如果我们仔细观察这两个中的第一个,我们会看到 publicnegpassword 以及 non-compliant 与 bitand:

一起使用
public =

  112  117   98  108  105   99

negpassword =

     0     0     0     0     0     0     0
     0     0     0     0     0     0     0
     0     0     0     0     0     0     0
     0     0     0     0     0     0     0
     0     0     0     0     0     0     0
     0     0     0     0     0     0     0

这两个必须至少是同一个维度。有关详细信息,请参阅 the reference for Bit-wise OR

我不太确定你想在这里实现什么,但不是因为 Matlab 有它自己的 bitxor 函数:

public = 'public';
password = 'passwd';
if length(public)== length(password)
    public = uint8(public);
    password = uint8(password);
    score = bitxor(public,password);
    public = dec2bin(public);
    password = char(password);
else
    fprintf('length not ok!\n' );
end

平时作业我是不给答案的,不过看来你差不多了。逻辑已经完成,这是我猜的重要部分。

关于代码,这里有一些错误。 dec2bin 函数会骗你。据我所知,matlab不支持二进制格式。 dec2bin 实际上将数字转换为 char 数组:(。但是,具有二进制格式的文本并不是进行按位运算的必要条件。我真的看不到 matlab 中二进制格式的用途,因为最小的大多数计算机架构的数据单位通常是一个字节。

您可以使用函数bitcmp(按位补码,按位非的另一种说法)来求反。其次,位运算也可以作用于向量。第三,可以将否定定义为一个变量,但是对于大多数处理器和操作系统来说,位操作是最便宜的,所以坦率地说,这对于只有两种用途是没有必要的。所以一切的内容就是你可以把事情简化很多。

ab = 'ab'; bb = 'bb';
ab=uint8(ab); bb=uint8(bb);
bitor(bitand(ab,bitcmp(bb)), bitand(bb,bitcmp(ab)))