diff options
| author | Louis Burda <quent.burda@gmail.com> | 2023-01-27 19:33:23 +0100 |
|---|---|---|
| committer | Louis Burda <quent.burda@gmail.com> | 2023-01-27 19:33:23 +0100 |
| commit | cdcdfbd7986b53744286c026a3a2f87e408caa93 (patch) | |
| tree | 08586438fb514da0b54019bdf46d650658c31d9d | |
| parent | cbe855db3e1ba0219ef019e703131b0533db8f09 (diff) | |
| download | hex-cdcdfbd7986b53744286c026a3a2f87e408caa93.tar.gz hex-cdcdfbd7986b53744286c026a3a2f87e408caa93.zip | |
Fix unhex for newlines
| -rw-r--r-- | Makefile | 2 | ||||
| -rw-r--r-- | hex.c | 10 | ||||
| -rw-r--r-- | unhex.c | 42 |
3 files changed, 34 insertions, 20 deletions
@@ -1,6 +1,8 @@ PREFIX ?= /usr/local BINDIR ?= /bin +CFLAGS = -O2 + all: hex hexv unhex clean: @@ -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]); @@ -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 |
