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");
}
}