Skip to content

Instantly share code, notes, and snippets.

@johnnyman727
Last active August 29, 2015 13:57
Show Gist options
  • Save johnnyman727/9924027 to your computer and use it in GitHub Desktop.
Save johnnyman727/9924027 to your computer and use it in GitHub Desktop.
JavaScript Intel Hex Parser For BlueGiga BLE Device Updates
var fs = require('fs');
function parseIntelHexData(path, callback) {
var hex = fs.readFileSync(path).toString();
console.log('loaded file');
// Split the file into lines
var hexLines = hex.split('\n');
// The last line is an empty string
hexLines.pop();
// initialize the buffer as large as it could be (to save time)
var buff = new Buffer(hexLines.length * 16);
// Start at 0
var buffPos = 0;
// Don't store data until we're at the right line
var startRecording = false;
// This start address is specific to BLE. Most people won't need it.
var startAddress = parseInt('0x1000', 16);
// For each line
for (var i = 0; i < hexLines.length; i++) {
// Grab the line
var line = hexLines[i];
// Save the bytecount
var byteCount = parseInt(line.substr(1, 2), 16);
// Save the address
var address = parseInt(line.substr(3, 4), 16);
// Save the record type
var recordType = parseInt(line.substr(7, 2), 16);
// If we hit the start line
if (address == startAddress) {
// Start recording
startRecording = true;
}
// If we are recording and this is a data record and there are data bytes
if (startRecording && recordType == 0 && byteCount) {
// First data byte is at byte 9
var startIndex = 9;
// For each byte
for (var j = 0; j < byteCount; j++) {
// Get the index of the next byte
var dataIndex = startIndex + (j * 2);
// Interpret two characters as a hex digit
buff.writeUInt8(parseInt(line.substr(dataIndex, 2), 16), buffPos);
// Increase our buffer position
buffPos++;
}
}
}
// Cut off any extra bytes (lines that didn't have data)
buff = buff.slice(0, buffPos);
console.log("Finished!", buff.length);
return buff;
}
module.exports = parseIntelHexData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment