1

我想使用密钥字符串对 C 中的字符串进行编码。该encodeMSG函数返回 int 数组,因此:
intArr[i] = the int value of msg[i] + the int value of key[i].
如果 key 字符串的长度比 msg 字符串短,它应该回到开头(循环)。

我不确定我应该怎么做,虽然它看起来不太复杂。
我也不确定我应该使用atoi(msg + i)还是像(int)(*(msg + i)).

int *encodeMSG(char *msg, char *key)
{
   int i, msgLen;
   int *encodedArr = (int *)malloc(strlen(msg) * sizeof(int));
   char *keyBackup = key;
   msgLen = (strlen(msg));

   for (i = 0; i < msgLen; ++i)
   {
       if (*(key + i) == '\0')
           key = keyBackup;

       *(encodedArr + i) = *(msg + i); //creating an integer-represented array of the char array [msg]
       *(encodedArr + i) += *(key + i); //adding the [key] array integer values to the integer-represented array of the message
   }

   return encodedArr;
}
4

3 回答 3

1

试试这个:

int *encodeMSG(char *msg, char *key)
{
    char *key0 = key;
    int *result = (int*) malloc( sizeof(int)*(strlen(msg)+1) );
      // +1 to include the final zero of msg
    int *result0 = result;
    while( *msg ) // i assume it's zero-terminated
    {
        *result++ = ((int)*msg) + ((int)*key);
        ++msg;
        ++key;
        if(!*key)key=key0; // reset it to the beginning of the key
    }
    *result = 0; // the final zero
    return result0;
}

这将直接使用 ascii 值, atoi 在这里没有用。请注意, *msg 是 msg 指向的实际字符。由于 msg 是以零结尾的,字符串的结尾是 0 的 false。同样适用于*key,当*key == 0(或!*key)时,只需将其重置为关键短语的开头。

顺便说一句:它返回一个 int[],比 msg 中的字符多 1 个 int,最后一个 int 为零。

于 2012-10-06T14:22:36.497 回答
0

如果您正在寻找 ASCII 编码,只需使用:

for(i=0; i<msglen; ++i)
  res[i] = msg[i] + key[i%key_len]

但是,如果您的字符包含一个数字,您可以简单地将其整数值作为

int a = ch - '0'    // if ch = '5' then value of a comes out to be 5

如果您不减去“0”,则 a 的值为 53(ASCII 值为“5”)

于 2012-10-06T14:02:50.280 回答
0

较短的版本:

int *encodeMSG(char *msg, char *key)
{
  int *result = (int*) malloc( sizeof(int)*(strlen(msg)+1) );
  int key_len = strlen(key);

  for(size_t i=0, msglen=strlen(msg); i<msglen; ++i )
     result[i] = msg[i] + key[i % key_len];

   result[i] = 0; // the final zero
   return result;
 }
于 2012-10-06T18:27:52.570 回答