Anyone fancy having a go at shrinking this C code? It's an implementation
of RSADSI's RC4 encryprion algorithm in 283 bytes. No, removing the
usage comment doesn't count :) Try not to degrade performance too much
either (ie, changing the size of the read buffer b to, say, 9 chars).
Note that it uses unsigned chars to accomplish implied modulo 256
arithmetic.
#define S,t=s[i],s[i]=s[j],s[j]=t, /* :usage: rc4 key <file; @RSADSI */
main(int c,char**v){unsigned char*p=*++v,s[256],b[4096],i=0,j=0,t;c=
strlen(p);while(s[i]=i,++i);while(j+=s[i]+p[i%c]S++i);j=0;while(c=read
(0,p=b,4096)){while(c--){j+=s[++i]S*p++^=s[t+=s[i]];}write(1,b,p-b);}}
There's this possibility, that saves one char, but it's none too
pleasing in that it adds a line:
#define W;while(
#define S,t=s[i],s[i]=s[j],s[j]=t, /* :usage: rc4 key <file; @RSADSI */
main(int c,char**v){unsigned char*p=*++v,s[256],b[4096],i=0,j=0,t;c=
strlen(p)W s[i]=i,++i)W j+=s[i]+p[i%c]S++i);j=0 W c=read
(0,p=b,4096)){W c--){j+=s[++i]S*p++^=s[t+=s[i]];}write(1,b,p-b);}}
Any ideas?
John.
: Any ideas?
: John.
well you could replace the S macro by
: #define S,s[i]^=s[j]^=s[i]^=s[j],
this saves you one char on the macro, and saves the var 't' -> one more char
:-)
now, for understanding the code I needed more time...
Carlos
>: #define S,s[i]^=s[j]^=s[i]^=s[j],
Cute, but completely wrong; this code may or may not do anything at all, may
not compile, and on a good compiler, will optimize into "s[i]=s[j],s[j]=0".
You may not modify the same object twice between sequence points, or use and
modify it between sequence points, unless the use is to determine the new
value, and has no other effects or relevance.
Please don't post clever tricks that don't work, and please don't post
anything at all until you've read the FAQ at least once. (It even covers
exactly this trick.)
-s
--
Peter Seebach - se...@solon.com - Copyright 1996 Peter Seebach.
Unix/C Wizard - send mail for help, or send money for consulting!
Unsolicited email is not welcome, and will be billed for at consulting rates.
The *other* C FAQ - http://www.solon.com/~seebs/c/c-iaq.html