这是之前提出的问题的扩展:link https://stackoverflow.com/questions/20851902/need-suggestion-on-code-conversion-to-matlab?noredirect=1#comment31280378_20851902。简而言之,我正在尝试将 C 程序转换为 Matlab,并寻求您的建议来改进代码,因为代码没有给出正确的输出。
C程序:
void prga(unsigned char S[], unsigned char out[], int len) {
int i=0,j=0,x,t;
unsigned char key;
for (x=0; x < len; ++x) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
t = S[i];
S[i] = S[j];
S[j] = t;
out[x] = S[(S[i] + S[j]) % 256];
}
}
Matlab程序:
function [out, i, j, S]=rc4out(i, j, S)
%for x = 1:length(key) % It should not work here as no key mentioned
i = mod( (i+1), 256);
j = mod( j + S(i), 256);
t = S(i);
S(i) = S(j+1);
S(j+1) = t;
out = mod(S(S(i) + S(j+1), 256));
EDIT:
试试这个,它的想法与 c 函数相同:S
应该>= 256
否则你会超过它mod()
可以返回这样的索引。我建议你改变256
在函数中lenght
提供解决这个问题。
在这里你不需要key
多变的。
function out = prga(S, len)
i=0; j=0; x=[]; t=[];
for x=0:len-1
i = mod(i+1, 256);
j = mod(j+S(i+1), 256);
t = S(i+1);
S(i+1) = S(j+1);
S(j+1) = t;
out(x+1) = S(mod(S(i+1)+S(j+1), 256)+1);
end
end
或者您可以使用key
控制循环的变量
function out = prga(S, key)
i=0; j=0; x=[]; t=[];
for x=0:length(key)-1
i = mod(i+1, 256);
j = mod(j+S(i+1), 256);
t = S(i+1);
S(i+1) = S(j+1);
S(j+1) = t;
out(x+1) = S(mod(S(i+1)+S(j+1), 256)+1);
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)