Last active
July 11, 2019 19:52
-
-
Save fhpriamo/6972af790bb53336712a7ca1a4b6aa77 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tcmrc | |
import ( | |
"bufio" | |
"bytes" | |
"fmt" | |
"os" | |
) | |
type HexFile struct { | |
os.File | |
dataBytesWritten int | |
writeBuffer *bufio.Writer | |
} | |
type DataRecord struct { | |
Reclen uint8 | |
LoadOffset uint16 | |
Data []byte | |
} | |
func (r *DataRecord) Checksum() int { | |
var sum uint8 = 0 | |
sum += r.Reclen | |
sum += uint8(r.LoadOffset / 256) | |
sum += uint8(r.LoadOffset % 256) | |
for _, d := range r.Data { | |
sum += uint8(d) | |
} | |
return int((^sum) + 1) | |
} | |
func (r *DataRecord) Format() string { | |
var buffer bytes.Buffer | |
buffer.WriteString(":") | |
buffer.WriteString(fmt.Sprintf("%02X", r.Reclen)) | |
buffer.WriteString(fmt.Sprintf("%04X", r.LoadOffset)) | |
buffer.WriteString("00") | |
for _, d := range r.Data { | |
buffer.WriteString(fmt.Sprintf("%02X", d)) | |
} | |
buffer.WriteString(fmt.Sprintf("%02X", r.Checksum())) | |
return buffer.String() | |
} | |
func (h *HexFile) WriteEOFRecord() { | |
h.writeLine(":00000001FF") | |
} | |
func (h *HexFile) WriteDataBytes(data []byte) { | |
r := new(DataRecord) | |
r.Data = data | |
r.Reclen = uint8(len(data)) | |
h.WriteDataRecord(r) | |
} | |
func (h *HexFile) WriteDataRecord(r *DataRecord) { | |
r.LoadOffset = uint16(h.dataBytesWritten) | |
h.writeLine(r.Format()) | |
h.dataBytesWritten += int(r.Reclen) | |
} | |
func (h *HexFile) Close() error { | |
h.WriteEOFRecord() | |
h.writeBuffer.Flush() | |
return h.File.Close() | |
} | |
func (h *HexFile) writeLine(str string) { | |
h.writeBuffer.WriteString(fmt.Sprintf("%s\n", str)) | |
} | |
func NewHexFile(fileName string) (*HexFile, error) { | |
file, err := os.Create(fileName) | |
if err != nil { | |
return nil, err | |
} | |
hex := &HexFile{ | |
File: *file, | |
dataBytesWritten: 0, | |
writeBuffer: bufio.NewWriter(file), | |
} | |
return hex, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment