| 1 | unit UIntelHexFile;
|
|---|
| 2 |
|
|---|
| 3 | interface
|
|---|
| 4 |
|
|---|
| 5 | uses
|
|---|
| 6 | UTextFileStream, SysUtils;
|
|---|
| 7 |
|
|---|
| 8 | type
|
|---|
| 9 | TArrayofByte = array of Byte;
|
|---|
| 10 |
|
|---|
| 11 | TIntelHexFile = class(TTextFileStream)
|
|---|
| 12 | public
|
|---|
| 13 | function ReadContent: TArrayOfByte;
|
|---|
| 14 | end;
|
|---|
| 15 |
|
|---|
| 16 |
|
|---|
| 17 | implementation
|
|---|
| 18 |
|
|---|
| 19 | { TIntelHexFile }
|
|---|
| 20 |
|
|---|
| 21 | function TIntelHexFile.ReadContent: TArrayOfByte;
|
|---|
| 22 | var
|
|---|
| 23 | Row: string;
|
|---|
| 24 | DataCount: Byte;
|
|---|
| 25 | RecordType: Byte;
|
|---|
| 26 | I: Integer;
|
|---|
| 27 | CRC: Byte;
|
|---|
| 28 | ComputedCRC: Byte;
|
|---|
| 29 | Address: Word;
|
|---|
| 30 | SegmentAddress: Word;
|
|---|
| 31 | ExtendedAddress: Word;
|
|---|
| 32 | EndOfFile: Boolean;
|
|---|
| 33 |
|
|---|
| 34 | function SplitString(var Text: string; Count: Word): string;
|
|---|
| 35 | begin
|
|---|
| 36 | Result := Copy(Text, 1, Count);
|
|---|
| 37 | Delete(Text, 1, Count);
|
|---|
| 38 | end;
|
|---|
| 39 |
|
|---|
| 40 | begin
|
|---|
| 41 | ExtendedAddress := 0;
|
|---|
| 42 | SegmentAddress := 0;
|
|---|
| 43 | EndOfFile := False;
|
|---|
| 44 | repeat
|
|---|
| 45 | ComputedCRC := 0;
|
|---|
| 46 | Row := ReadLn;
|
|---|
| 47 | if SplitString(Row, 1) <> ':' then raise Exception.Create('File corrupted');
|
|---|
| 48 | for I := 0 to (Length(Row) div 2) - 2 do
|
|---|
| 49 | ComputedCRC := ComputedCRC + StrToInt('$' + Row[I * 2 + 1] + Row[I * 2 + 2]);
|
|---|
| 50 | ComputedCRC := not (ComputedCRC ) + 1;
|
|---|
| 51 |
|
|---|
| 52 | DataCount := StrToInt('$' + SplitString(Row, 2));
|
|---|
| 53 | Address := StrToInt('$' + SplitString(Row, 4)) + (SegmentAddress shl 4) +
|
|---|
| 54 | (ExtendedAddress shl 16);
|
|---|
| 55 | RecordType := StrToInt('$' + SplitString(Row, 2));
|
|---|
| 56 | case RecordType of
|
|---|
| 57 | 0: begin // Data
|
|---|
| 58 | if Length(Result) < (Address + DataCount) then
|
|---|
| 59 | SetLength(Result, Address + DataCount);
|
|---|
| 60 | for I := 0 to DataCount - 1 do begin
|
|---|
| 61 | Result[Address + I] := StrToInt('$' + SplitString(Row, 2));
|
|---|
| 62 | end;
|
|---|
| 63 | end;
|
|---|
| 64 | 1: begin // End-of-file
|
|---|
| 65 | EndOfFile := True;
|
|---|
| 66 | end;
|
|---|
| 67 | 2: begin // Segment address
|
|---|
| 68 | SegmentAddress := StrToInt('$' + SplitString(Row, 4));
|
|---|
| 69 | ExtendedAddress := 0;
|
|---|
| 70 | end;
|
|---|
| 71 | 4: begin // Linear extended address
|
|---|
| 72 | ExtendedAddress := StrToInt('$' + SplitString(Row, 4));
|
|---|
| 73 | SegmentAddress := 0;
|
|---|
| 74 | end;
|
|---|
| 75 | end;
|
|---|
| 76 | CRC := StrToInt('$' + SplitString(Row, 2));
|
|---|
| 77 | if CRC <> ComputedCRC then raise Exception.Create('Checksum error');
|
|---|
| 78 | until Eof or EndOfFile;
|
|---|
| 79 | end;
|
|---|
| 80 |
|
|---|
| 81 | end.
|
|---|