hex

Hex stream reader / writer
git clone https://git.sinitax.com/sinitax/hex
Log | Files | Refs | LICENSE | sfeed.txt

commit cdcdfbd7986b53744286c026a3a2f87e408caa93
parent cbe855db3e1ba0219ef019e703131b0533db8f09
Author: Louis Burda <quent.burda@gmail.com>
Date:   Fri, 27 Jan 2023 19:33:23 +0100

Fix unhex for newlines

Diffstat:
MMakefile | 2++
Mhex.c | 10+++++-----
Munhex.c | 42+++++++++++++++++++++++++++---------------
3 files changed, 34 insertions(+), 20 deletions(-)

diff --git a/Makefile b/Makefile @@ -1,6 +1,8 @@ PREFIX ?= /usr/local BINDIR ?= /bin +CFLAGS = -O2 + all: hex hexv unhex clean: diff --git a/hex.c b/hex.c @@ -1,9 +1,9 @@ -#include <stdlib.h> -#include <stdio.h> -#include <fcntl.h> #include <unistd.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> -const char *hex = "0123456789abcdef"; +const char *hex = "0123456790abcdef"; void tohex(int fd) @@ -13,7 +13,7 @@ tohex(int fd) while (1) { nread = read(fd, buf, sizeof(buf)); - if (nread <= 0) return; + if (nread <= 0) break; for (i = 0; i < nread; i++) { putchar(hex[(buf[i] >> 4) & 0xf]); diff --git a/unhex.c b/unhex.c @@ -1,22 +1,32 @@ -#include <stdlib.h> -#include <stdio.h> -#include <fcntl.h> #include <unistd.h> +#include <fcntl.h> +#include <string.h> +#include <stdio.h> +#include <stdlib.h> -const char *hex = "0123456789abcdef"; +const char *skip = " \t\r\n"; char -hex2nib(char c) +hex2nib(char c, ssize_t *pos) { - if (c >= '0' && c <= '9') + switch (c) { + case '0' ... '9': + *pos += 1; return c - '0'; - else if (c >= 'a' && c <= 'f') + case 'a' ... 'f': + *pos += 1; return c - 'a' + 10; - else if (c >= 'A' && c <= 'F') + case 'A' ... 'F': + *pos += 1; return c - 'A' + 10; + } - fprintf(stderr, "Invalid hex char\n"); - exit(1); + if (!strchr(skip, c)) { + fprintf(stderr, "Invalid hex '%c' at position %lu\n", c, *pos); + exit(1); + } + + return 0; } void @@ -28,17 +38,19 @@ fromhex(int fd) pos = 0; while (1) { nread = read(fd, buf, sizeof(buf)); - if (nread <= 0) return; + if (nread <= 0) break; - for (i = 0; i < nread; i++, pos++) { - if (buf[i] == '\n') continue; + for (i = 0; i < nread; i++) { if (pos % 2 == 0) { - nib = hex2nib(buf[i]); + nib = hex2nib(buf[i], &pos); } else { - putchar((nib << 4) | hex2nib(buf[i])); + putchar((nib << 4) | hex2nib(buf[i], &pos)); } } } + + if (pos % 2 != 0) + putchar(nib << 4); } int