Run-length encoding/C: Difference between revisions

no edit summary
No edit summary
 
Line 10:
 
Also: In this implementation, '''string'''s are assumed to be null terminated. Hence cannot contain the ''null'' character as data.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 109:
printf("\n");
return 0;
}</langsyntaxhighlight>
Output:
<pre>
Line 123:
Since repeat counter must fit a single byte in this implementation, it can't be greater than 255, so a byte repeated more than 255 times generates in the compressed stream more than 2 bytes (4 bytes if the length of the repeated byte sequence is less than 511 and so on)
 
<syntaxhighlight lang="c">
<lang c>int rle_encode(char *out, const char *in, int l)
{
int dl, i;
Line 145 ⟶ 146:
*out++ = i; *out++ = cp; dl += 2;
return dl;
}
}</lang>
</syntaxhighlight>
 
'''Decoding function'''
 
<syntaxhighlight lang="c">
<lang c>int rle_decode(char *out, const char *in, int l)
{
int i, j, tb;
Line 161 ⟶ 164:
}
return tb;
}
}</lang>
</syntaxhighlight>
 
'''Usage example'''
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 184 ⟶ 188:
free(d); free(oc);
return 0;
}
}</lang>
</syntaxhighlight>
 
In the following codes, encoding and decoding are implemented as "filters" which compress/decompress standard input to standard output writing ASCII strings; they will work as long as the input has no ASCII digits in it, and the compressed/original ratio of a "single group" will be less than or equal to 1 as long as the ASCII decimal representation's length of the repeat counter will be shorter than the length of the "group". It should be so except in the case the group is a single isolated character, e.g. B gives 1B (one byte against two compressed bytes)
Line 190 ⟶ 195:
'''Encoding filter'''
 
<syntaxhighlight lang="c">
<lang c>#include <stdio.h>
 
int main()
Line 207 ⟶ 213:
printf("%d%c", i, cp);
return 0;
}
}</lang>
</syntaxhighlight>
 
'''Decoding filter'''
 
<syntaxhighlight lang="c">
<lang c>#include <stdio.h>
 
int main()
Line 221 ⟶ 229:
}
return 0;
}
}</lang>
</syntaxhighlight>
 
'''Final note''': since the repeat counter value 0 has no meaning, it could be used as it would be 256, so extending by one the maximum number of repetitions representable with a single byte; or instead it could be used as a special marker to encode in a more efficient way (long) sequences of ''isolated characters'', e.g. "ABCDE" would be encoded as "1A1B1C1D1E"; it could be instead encoded as "05ABCDE".