需要将代码转换为Matlab_extension 1的建议 [英] Need suggestion on Code conversion to Matlab_extension 1

查看:56
本文介绍了需要将代码转换为Matlab_extension 1的建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是先前询问的问题的扩展:链接.简而言之,我正在尝试将C程序转换为Matlab,并寻求您的建议以改进代码,因为代码未提供正确的输出.

This is an extension of the previously asked question: link. In a short, I am trying to convert a C program into Matlab and looking for your suggestion to improve the code as the code is not giving the correct output.

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));

推荐答案

尝试此操作与c函数的想法相同:S的长度应为>= 256,否则将超出该范围,因为mod()可能会返回此类索引.建议您使用提供的lenght更改功能中的256.

Try this it do the same think as the c function: The lengh of S should be >= 256 or you will exceed it as mod() could return such index. I suggest you to change 256 in the function with the lenght provided to solve this issue.

这里不需要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变量来控制循环

Or you can use the key variable to controle the loop

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

这篇关于需要将代码转换为Matlab_extension 1的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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