Motorola S-record is a file format, created by Motorola, that conveys binary information in ASCII hex text form. This file format may also be known as SRECORD, SREC, S19, S28, S37.

It is(was) commonly used for programming flash memory in microcontrollers, EPROMs, EEPROMs, and other types of programmable logic devices. In a typical application, a compiler or assembler converts a program’s source code (such as C or assembly language) to machine code and outputs it into a HEX file. The HEX file is then imported by a programmer to “burn” the machine code into non-volatile memory, or is transferred to the target system for loading and execution.

(ref: Wikipedia)

Below is a simple code snippet which converts the .mot file into a byte array:

public static List<byte[]> ConvertToBytes(string inputpath, out UInt16 checksum)
{
    List<byte[]> bytes = new List<byte[]>();
    string[] motFile = System.Text.Encoding.UTF8.GetString(File.ReadAllBytes(inputpath)).Split(new string[] { "\r\n" }, StringSplitOptions.None);

    checksum = 0;
    UInt32 num = 0;
    for (int i = 0; i < motFile.Length; i++)
    {
	if (motFile[i].Contains("S3"))
        {
			byte[] tmpb = motFile[i].Substring(4, motFile[i].Length - 4).HexToByteArray();
            byte[] q = tmpb.SubArrayDeepClone(4, tmpb.Length - 5);
            checksum += (UInt16)q.SumUpBytes();
            num += (UInt32)q.Length;
            bytes.Add(new byte[] { 0x03, (byte)tmpb.Length }.CombineWith(tmpb));
        }
    }

    checksum = (UInt16)(((UInt32)checksum + (0x0003FFFF + 1 - num - 0x00008100) * 0xFF) & 0xFFFF);
    return bytes;
}


//////////////////////////////////////////////////////////////////////////////////////
// Required Extensions 
//////////////////////////////////////////////////////////////////////////////////////

public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
    try
    {
	T[] arrCopy = new T[(data.Length - index) > length ? length : data.Length - index];
        Array.Copy(data, index, arrCopy, 0, (data.Length - index) > length ? length : data.Length - index);
        using (MemoryStream ms = new MemoryStream())
        {
			var bf = new BinaryFormatter();
            bf.Serialize(ms, arrCopy);
            ms.Position = 0;
            return (T[])bf.Deserialize(ms);
        }
    }
    catch (Exception)
    {
	return default(T[]);
    }
}
		
public static int SumUpBytes(this byte[] t)
{
    int res = 0;
    for (int i = 0; i < t.Length; i++)
        res += t[i];
    return res;
}
Author

Write A Comment