Archived

This topic is now archived and is closed to further replies.

Perl -> C function

This topic is 5114 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi. I'm trying to convert an encryption function from Perl to C. This is the Perl:
$mask = "1234567890abcdefghijklmnopqrstuvwxyz";
#xor method
sub EnDecrypt {
  my $str = shift;
  #encrypt (or decrypt!) by xor
  my $result = "";
  for($n=0;$n<length($str);$n++){
    $result .= substr($str, $n, 1) ^ substr($mask, $n % length($mask), 1);
  };
  return $result;
};
And this is what I've managed to do so far. There isn't much more to do, i'm just unsure of what "shift" is, and what to replace substr() with:
#define MASK "1234567890abcdefghijklmnopqrstuvwxyz"

char* EnDecrypt() 
{
	char str = shift;

	char result[255];
  
	int i;

	for(int i=0; i<length(str); i++)
	{
		result = substr(str, i, 1) ^ substr(MASK, i % length(MASK), 1);
	}
  

	return result;
}
[edited by - Shard on December 14, 2003 1:02:20 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
What''s the first AP up to? Seriously, good luck, but I think a better language ;P should do the job better. (Think C++, Java or C#).

Share this post


Link to post
Share on other sites
shift, does something magically, see this example:

In perl
sub magic {
$arrrrrrr = shift;
print $atttttttrrrrrrrrrrrr;
}

In C
void magic(const char * arttttrrrr) {
puts(arrrtttrr);
}


shift without any arguments is equal to shift $.:,_>$<@ or something, that variable is the arguments passed to the function.

substr... just write your own

Share this post


Link to post
Share on other sites

void EnDecrypt(char* in, char* out, int length, char *mask, int mask_length)
{
for(int i=0; i < length; ++i)
{
out[i] = in[i] ^ mask[i % mask_length];
}
}

Does that do what you need?

Share this post


Link to post
Share on other sites
quote:
Original post by Leffe
shift without any arguments is equal to shift $.:,_>$<@ or something, that variable is the arguments passed to the function.

substr... just write your own


shift with no args, in a function, is equivalent to "shift @_". Not complicated. It simply returns the first item of the array passed to it, which in this case is the default array all the args to the sub live in. (Outside of a function it is equivalent to "shift @ARGV").

And thats a really, really horrible perl function. It looks like someone tried to write C in perl. So ugly.

Share this post


Link to post
Share on other sites