#Need help to understand and solve C# / Hyper-Optimized Telemetry

2 messages · Page 1 of 1 (latest)

cobalt musk
#

I have been trying to solve this problem for a while and I generally cannot figure out how the Byte conversion works and it is having me fed up with it at this point.
I have tried using ChatGPT when I didn't understand it myself and not getting any more understanding from that.

Here is my current codesnippet:

public static class TelemetryBuffer
{
    public static byte[] ToBuffer(long reading)
    {
        byte[] buffer = new byte[9];
        byte[] valueBytes;
        byte prefix;

        if (reading >= 0 && reading <= ushort.MaxValue)
        {
            valueBytes = BitConverter.GetBytes((ushort)reading);
            prefix = 2;
        }
        else if (reading >= short.MinValue && reading <= -1)
        {
            valueBytes = BitConverter.GetBytes((short)reading);
            prefix = (byte)(256-2);
        }
        else if (reading >= 0 && reading <= int.MaxValue)
        {
            valueBytes = BitConverter.GetBytes((int)reading);
            prefix = 4;
        }
        else if (reading >= int.MinValue && reading <= -32769)
        {
            valueBytes = BitConverter.GetBytes((int)reading);
            prefix = (byte)(256 - 4);
        }
        else if (reading >= 0 && reading <= uint.MaxValue)
        {
            valueBytes = BitConverter.GetBytes((uint)reading);
            prefix = 4;
        }
        else if (reading >= 0)
        {
            valueBytes = BitConverter.GetBytes((ulong)reading);
            prefix = 8;
        }
        else
        {
            valueBytes = BitConverter.GetBytes(reading);
            prefix = (byte)(256 - 8);
        }

        if (BitConverter.IsLittleEndian)
        {
            Array.Reverse(valueBytes);
        }

        buffer[0] = prefix;
        Array.Copy(valueBytes, 0, buffer, 1, valueBytes.Length);
        return buffer;
    }

    public static long FromBuffer(byte[] buffer)
    {
        throw new NotImplementedException("Please implement the static TelemetryBuffer.FromBuffer() method");
    }
}
dark echo
#

Hi Twine! I won't give the full answer, we're discouraged from doing that, but I did notice that commenting out your if clause testing for IsLittleEndian has a dramatic effect on the number of tests passing 🙂 . Obviously you haven't done the FromBuffer method yet, but you may find that one is simpler anyway.