Skip to content

Instantly share code, notes, and snippets.

@detorto
Created May 31, 2017 12:51
Show Gist options
  • Save detorto/6cea1b0787c73d76121baf1931ef383f to your computer and use it in GitHub Desktop.
Save detorto/6cea1b0787c73d76121baf1931ef383f to your computer and use it in GitHub Desktop.
binary to intelhex converter using cpp
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;
const int kECBHeaderLength = 36;
//"srec_cat $ACTIVATE_CFG{BL_PATH}.noecb -bin -offset 0x1000 -o $ACTIVATE_CFG{BL_PATH}.hex -intel;"
std::string loadFile(const std::string &filename)
{
std::ifstream file(filename.c_str());
std::string str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
return str;
}
std::string cutECBHeader(const std::string &data)
{
return data.substr(kECBHeaderLength);
}
std::string hexStr(std::string data)
{
std::string ret;
char hex_byte[3];
int i;
for (i = 0; i < data.size(); i++)
{
sprintf(hex_byte, "%02x", (unsigned char) data[i]);
ret += hex_byte;
}
std::transform(ret.begin(), ret.end(), ret.begin(), ::toupper);
return ret;
}
std::string intToHex(int i)
{
std::stringstream sstream;
sstream << std::hex << i;
std::string ret = sstream.str();
std::transform(ret.begin(), ret.end(), ret.begin(), ::toupper);
return ret;
}
std::string calcCheckSum(const std::string &hexdata)
{
char summ = 0;
for (int i =0; i< hexdata.size(); i+=2)
{
std::string hex_byte = hexdata.substr(i,2);
int byte;
std::stringstream ss;
ss << std::hex << hex_byte;
ss >> byte;
summ+=byte;
//cout << "Hex: "<<hex_byte<<" Int: "<<byte <<" Sum: "<<summ<<endl;
}
summ = 0x100 - summ;
return hexStr(string(1,summ));
}
std::string convertToIntelHex(const std::string &data, int offset)
{
int current_address = offset;
std::string out;
// add Extended Linear Address Record,
out = ":020000040000FA\n";
int current_byte = 0;
while (current_byte < data.size())
{
//add byte count
std::string start_section = "20";
//add current address
start_section += intToHex(current_address);
//add record type
start_section += "00";
std::string data_section = hexStr(data.substr(current_byte, 32));
std::string checksumm = calcCheckSum(start_section + data_section);
//make result string
std::string toapp = ":"+start_section+data_section+checksumm+"\n";
out+=toapp;
current_byte += 32;
current_address += 32;
}
//add end of file
out += ":00000001FF";
return out;
}
int main(int argc, char *argv[])
{
std::string data = loadFile(argv[1]);
data = cutECBHeader(data);
std::string out = convertToIntelHex(data, 0x1000);
cout << out<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment