I want to encode a string in C using a key string.
The encodeMSG
function returns int array, so that:
intArr[i] = the int value of msg[i] + the int value of key[i]
.
If the length of the key string is shorter the the msg string, it should go back to the beginning (cycle).
I'm not sure how I should do this although it doesn't seem too complicated.
I also wasn't sure whether I should use atoi(msg + i)
or a simple cast like (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;
}