Advertisements

Useful Hex and Binary File Utilities

I’m doing some work with a one-off ROM reader & EPROM programmer, so it’s once again time to mess around with Intel HEX files, raw binary images, and the like.

The key routine (which runs on an Arduino Decimila) to dump a ROM in HEX format goes like this, with all the constants & variables & functions doing the obvious things:

void DumpHC641(void) {

word Address,Offset;
byte DataRd,Checksum;

 for (Address = 0; Address < ROM_SIZE; Address += IHEX_BYTES) {
  sprintf(PrintBuffer,":%02X%04X00",IHEX_BYTES,(word)Address);           // emit line header
  Serial.print(PrintBuffer);
  Checksum = IHEX_BYTES + lowByte(Address) + highByte(Address) + 0x00;   // record type 0x00
  for (Offset = 0; Offset < IHEX_BYTES; ++Offset) {
   digitalWrite(PIN_HEARTBEAT,HIGH);
   DataRd = ReadHC641(Address + Offset);
   digitalWrite(PIN_HEARTBEAT,LOW);
   Checksum += DataRd;
   sprintf(PrintBuffer,"%02X",DataRd);                                   // data byte
   Serial.print(PrintBuffer);
  }
  Checksum = -Checksum;                                                  // two's complement
  sprintf(PrintBuffer,"%02X",Checksum);
  Serial.println(PrintBuffer);
 }
 Serial.println(":00000001FF");                                          // emit end-of-file line
}

So getting an Intel HEX file is just a matter of capturing the serial output, whacking off any debris on either side of the main event, and saving it.

The srec_cat program handles conversions among a myriad formats, most of which I can’t even pronounce. The few I use go a little something like this:

srec_cat mumble.hex -intel -o mumble.bin -binary
srec_cat mumble.bin -binary -o mumble.hex -intel
srec_cat mumble.bin -binary -o mumble.txt -hex_dump
srec_cat -generate 0x0000 0x2000 -constant 0x00 -o mumble.txt -intel

It’s sometimes handy to apply srec_cat to a group of similarly suffixed files, in which case some Bash string chopping comes in handy. For example, to convert some hex files into binary:

for f in 27HC641*hex ; do echo ${f%%hex} ; srec_cat "$f"  -intel -o "${f%%hex}"bin -binary ; done

Good old diff works fine on text files, but in this case it’s better to see which bytes have changed, rather than which lines (which don’t apply in the context of a binary file). The vbindiff program looks great on a portrait-mode display.

I don’t do much binary editing, but tweak serves my simple needs. Confusingly, members of this class of program are called “hex editors”, but they really work on binary files.

There’s also diff3, for those rare cases where you must mutually compare three text files. Makes my head spin every time…

All those programs are likely packages in your favorite Linux distro.

Advertisements