Matlab程序在一个函数中显示不正确的结果 [英] Matlab program is showing incorrect result in one function

查看:201
本文介绍了Matlab程序在一个函数中显示不正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序是另一个C程序的转换版本.函数rc4key显示正确的结果,但是函数prga显示错误的结果(与C和正确的程序相比),我尝试了很长时间,但无法理解j0为什么显示178、255、255、255、255而不是178、174、22、42、76.非常需要您的建议和意见.我在此函数中使用了rc4('Hello','Hi'):

This below program is a converted version from another C program. Function rc4key is showing correct result but function prga is showing incorrect result (comparing to the C, the correct program), I am trying for quite long time but can't understand why the j0 is showing 178, 255, 255, 255, 255 instead of 178, 174, 22, 42, 76. Your suggestion and input is very much needed. I used rc4('Hello','Hi') in this function:

function ef = rc4(pf,ki)%Please ignore this function for this time being
s = rc4key(ki);
disp(s);
s = uint8(s);
j0 = 0;
i0 = 0;
r = prga(s, pf);
disp(r);
v = uint8(pf);
C = bitxor(v,r);
disp(C);
data_show = dec2hex(C);
ef = data_show;

function sc=rc4key(key)%This function is showing correct result
le = length(key);
sc = 0:255;
j0 = 0;
% scramble the key schedule
for i0 = 0:255
    k0 = floor(mod( key( floor(mod(i0,le))+1 ), 256));
    j0 = floor(mod( j0 + k0 + sc(i0+1), 256));
    disp(j0);
    tm = sc(i0+1);
    sc(i0+1) = sc(j0+1);
    sc(j0+1) = tm;
end

%This function is showing incorrect result in below mentioned section
function r = prga(sc, data)
i0=0; j0=0; x=[]; t=[];
for x=0:length(data)-1%upto this ok
    i0 = mod( (i0+1), 256);%upto this ok
    disp(sc(i0+1));%this shows 178, 252, 104, 20, 34 which is correct value


    %j0 = j0 + sc(i0+1);%This also shows incorrect value as below (i.e.178, 255, 255, 255, 255)
    j0 = mod( j0 + sc(i0+1), 256);%It should show: 178, 174, 22, 42, 76
    %whereas j0 is showing 178, 255, 255, 255, 255
    disp(j0);


    tm = sc(i0+1);
    sc(i0+1) = sc(j0+1);
    sc(j0+1) = tm;
    r = sc(j0+1);%Not crucial for this time being
    %r(x+1) = sc(mod( sc(i0+1) + sc(j0+1), 256)+1);
end

我期望: j0应显示:178、174、22、42、76,而j0应显示178、255、255、255、255.

I am expecting: The j0 should show: 178, 174, 22, 42, 76 whereas j0 is showing 178, 255, 255, 255, 255.

到目前为止,我已经尝试过:我试图更改rc4key函数中sc的值,仅在单独的工作表中检查了prga函数-那时显示正确的结果,但是当我尝试使用完整程序(这是必需的),它显示255、255....

What I have tried so far: I have tried to change the value of sc in rc4key function, checked only the prga function in separate worksheet - This shows correct result that time, But when I am trying for full program (which is necessary) it is showing that 255, 255....

推荐答案

您的问题是您将数据转换为uint8. Matlab为此添加了以下内容:255 + 1 => 255

your problem is that you cast your data to uint8. Matlab does the addition like this for these: 255+1 => 255

快速而肮脏的修复程序:只需注释掉以下行:s = uint8(s);

Quick and dirty fix: Just comment out the line: s = uint8(s);

这篇关于Matlab程序在一个函数中显示不正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆