Skip to content

Instantly share code, notes, and snippets.

@HeatXD
Created September 4, 2022 00:02
Show Gist options
  • Save HeatXD/dd33d9767aaefb75d12d820c0bb446be to your computer and use it in GitHub Desktop.
Save HeatXD/dd33d9767aaefb75d12d820c0bb446be to your computer and use it in GitHub Desktop.
RunLengthEncoding C#
private static List<byte> RLEEncode(List<byte> toEncode)
{
var bytes = new List<byte>();
byte count = 1;
byte current = toEncode[0];
for (int i = 0; i < toEncode.Count; i++)
{
if (current == toEncode[i] && count != byte.MaxValue)
{
if ( i != 0)
{
count++;
}
}
else
{
bytes.Add(count);
bytes.Add(current);
count = 1;
current = toEncode[i];
}
}
bytes.Add(count);
bytes.Add(current);
return bytes;
}
private static List<byte> RLEDecode(List<byte> data)
{
var result = new List<byte>();
for (int i = 0; i < data.Count; i += 2)
{
for (int j = 0; j < data[i]; j++)
{
result.Add(data[i + 1]);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment