52 lines
1.5 KiB
C

#include <stdio.h>
#include <string.h>
static int hex_digit(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
int main(int argc, char **argv) {
unsigned char payload[16];
int state = 0, length = 0, count = 0, checksum = 0;
for (int arg = 1; arg < argc; ++arg) {
size_t size = strlen(argv[arg]);
if (size % 2) return 2;
for (size_t pos = 0; pos < size; pos += 2) {
int hi = hex_digit(argv[arg][pos]);
int lo = hex_digit(argv[arg][pos + 1]);
if (hi < 0 || lo < 0) return 2;
int byte = hi * 16 + lo;
if (state == 0) {
if (byte > 16) {
puts("ERR");
continue;
}
length = byte;
count = 0;
checksum = byte;
state = length ? 1 : 2;
} else if (state == 1) {
payload[count++] = (unsigned char)byte;
checksum ^= byte;
if (count == length) state = 2;
} else {
if (byte != checksum) {
puts("ERR");
} else {
for (int i = 0; i < length; ++i) printf("%02x", payload[i]);
putchar('\n');
}
state = 0;
}
}
}
if (state) {
puts("INCOMPLETE");
return 1;
}
return 0;
}