summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLouis Burda <quent.burda@gmail.com>2023-01-27 19:33:23 +0100
committerLouis Burda <quent.burda@gmail.com>2023-01-27 19:33:23 +0100
commitcdcdfbd7986b53744286c026a3a2f87e408caa93 (patch)
tree08586438fb514da0b54019bdf46d650658c31d9d
parentcbe855db3e1ba0219ef019e703131b0533db8f09 (diff)
downloadhex-cdcdfbd7986b53744286c026a3a2f87e408caa93.tar.gz
hex-cdcdfbd7986b53744286c026a3a2f87e408caa93.zip
Fix unhex for newlines
-rw-r--r--Makefile2
-rw-r--r--hex.c10
-rw-r--r--unhex.c42
3 files changed, 34 insertions, 20 deletions
diff --git a/Makefile b/Makefile
index 775c44c..e0c9c82 100644
--- 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
index c0f7fc2..3ce0467 100644
--- 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
index cb276e0..d1f13b3 100644
--- 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