User Tools

Site Tools


intel_hex_and_the_checksum

The code below is adapted from work here:-

https://www.pjrc.com/tech/8051/ihex.c

/* Intel HEX read/write functions, Paul Stoffregen, paul@ece.orst.edu */ /* This code is in the public domain. Please retain my name */

https://www.fischl.de/hex_checksum_calculator/

parse_hex_line.c
#include <stdio.h>
#include <string.h>
 
int parse_hex_line(theline, bytes, addr, num, code)
char *theline;
int *addr, *num, *code, bytes[];
{
	int sum, len, cksum;
	char *ptr;
 
	*num = 0;
	if (theline[0] != ':') return 0;
	if (strlen(theline) < 11) return 0;
	ptr = theline+1;
	if (!sscanf(ptr, "%02x", &len)) return 0;
	ptr += 2;
	if ( strlen(theline) < (11 + (len * 2)) ) return 0;
	if (!sscanf(ptr, "%04x", addr)) return 0;
	ptr += 4;
	  /* printf("Line: length=%d Addr=%d\n", len, *addr); */
	if (!sscanf(ptr, "%02x", code)) return 0;
	ptr += 2;
	sum = (len & 255) + ((*addr >> 8) & 255) + (*addr & 255) + (*code & 255);
	while(*num != len) {
		if (!sscanf(ptr, "%02x", &bytes[*num])) return 0;
		ptr += 2;
		sum += bytes[*num] & 255;
		(*num)++;
		if (*num >= 256) return 0;
	}
	if (!sscanf(ptr, "%02x", &cksum)) return 0;
	int twos = sum;
 
	// twos = twos - 1;
	// twos = twos ^ 0xFF;
 
	twos = twos ^ 0xFF;
	twos = twos + 1;
 
	printf("%#04x\n", twos&255);
 
	return 0;
}
 
int main(int argc, char* argv[])
{
int addr, n, status, bytes[256];
parse_hex_line(argv[1], bytes, &addr, &n, &status);
return 0;
}
intel_hex_and_the_checksum.txt · Last modified: 2021/10/27 04:47 (external edit)