Search code examples
c#structrun-length-encoding

How should I run an rle algorithm on a struct array?


I have a bunch of arrays of structs. Each struct contains 3 bytes and an sbyte.

For easier understanding here's a small code.

public class Container
{
    public A[] structs;
}

public struct A
{
    public byte a;
    public byte b;
    public byte c;
    public sbyte d;

    public A(byte a, byte b, sbyte d)
    {
       this.a = a;
       this.b = b;
       this.c = b;
       this.d = d;
    }
}

Now I have tons of these structs, therefore I would like to use RLE in order to compress it and use less memory.

On starting the program, a method procedurally generates values for the variables, then performs calculations on them. After that, the arrays are rarely used, but it's still necessary to "keep them alive".

I tried to convert the structs to uints using binary concatenation, but it wasn't the best solution. I've been thinking of converting the values to strings, but I think it would be very imperformant.

There's no way using bytes instead of sbytes.

What do you think would be the best solution to compress the arrays using RLE? Thanks in advance.


Solution

  • There's no way using bytes instead of sbytes.

    Why? You can cast sbyte to byte and backward.

    Save you data like uint and generate structs when they need

    public struct A
    {
        public byte a;
        public byte b;
        public byte c;
        public sbyte d;
    
        public A(uint value)
        {
           this.a = (byte)(value >> 24);
           this.b = (byte)(value >> 16);
           this.c = (byte)(value >> 8);
           this.d = (sbyte)value;
        }
    
        public uint Value => (uint)this.a << 24 | (uint)this.b << 16 | (uint)this.c << 8 | (uint)this.d;
    }