28 lines
817 B
Plaintext
28 lines
817 B
Plaintext
code real RlOut=48, Ln=54; \intrinsic routines
|
|
string 0; \use zero-terminated strings
|
|
|
|
func StrLen(A); \Return number of characters in an ASCIIZ string
|
|
char A;
|
|
int I;
|
|
for I:= 0, -1>>1-1 do
|
|
if A(I) = 0 then return I;
|
|
|
|
func real Entropy(Str); \Return Shannon entropy of string
|
|
char Str;
|
|
int Len, I, Count(128);
|
|
real Sum, Prob;
|
|
[Len:= StrLen(Str);
|
|
for I:= 0 to 127 do Count(I):= 0;
|
|
for I:= 0 to Len-1 do \count number of each character in string
|
|
Count(Str(I)):= Count(Str(I)) + 1;
|
|
Sum:= 0.0;
|
|
for I:= 0 to 127 do
|
|
if Count(I) # 0 then \(avoid Ln(0.0) error)
|
|
[Prob:= float(Count(I)) / float(Len); \probability of char in string
|
|
Sum:= Sum + Prob*Ln(Prob);
|
|
];
|
|
return -Sum/Ln(2.0);
|
|
];
|
|
|
|
RlOut(0, Entropy("1223334444"))
|