commit: aaced5a847f17d43b56cc1b0605d51ae01af1d6e
parent: 75d716f6d1d037a23b53c038981df38e6527de28
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Thu, 9 Apr 2020 11:33:30 +0200
bin/xcd: Make similar to od -A x -t x1z -v
Diffstat:
M | src/xcd.c | 40 | ++++++++++++++++++++++++++-------------- |
1 file changed, 26 insertions(+), 14 deletions(-)
diff --git a/src/xcd.c b/src/xcd.c
@@ -1,9 +1,11 @@
// Copyright 2018-2020 Haelwenn (lanodan) Monnier <contact@hacktivis.me>
// Distributed under the terms of the CC-BY-SA-4.0 license
-#include <stdio.h> /* getchar(), putchar(), snprintf(), printf() */
+#include <stdio.h> /* printf(), fread() */
#include <math.h> /* sin() */
-#include <stdint.h>
+#include <stdint.h> /* uint8_t */
+#include <string.h> /* memset() */
+#include <ctype.h> /* isprint() */
void rainbow(double freq, int i) {
uint8_t red, green, blue;
@@ -14,38 +16,48 @@ void rainbow(double freq, int i) {
blue = sin(freq*i + 4*pi/3) * 127 + 128;
printf("[38;2;%02d;%02d;%02dm", red, green, blue);
- //printf("[48;2;%02d;%02d;%02dm", red, green, blue);
- // TODO: Replace to sprintf?
}
int main(void) {
int cols = 0, bytes = 0;
+ int line_width = 16;
double freq = 0.2;
- char c;
+ char c, line[line_width];
+
+ memset(&line, 0, line_width);
printf("[48;2;0;0;0m");
rainbow(freq, bytes);
- printf("%08x ", bytes);
- while((c = getc(stdin)) != EOF)
+ printf("%06x ", bytes);
+ while(fread(&c, 1, 1, stdin) > 0)
{
- if(cols >= 16) {
+ if(cols >= line_width) {
cols = 0;
+
+ printf(" >%s<", line);
+ memset(&line, 0, line_width);
+
rainbow(freq, bytes);
- printf("\n%08x ", bytes);
- } else {
- if(cols > 0 && ((cols % 2) == 0)) printf(" ");
- if(cols > 0 && ((cols % 8) == 0)) printf(" ");
+ printf("\n%06x ", bytes);
}
rainbow(freq, c);
- printf("%02X", c);
+ printf("%02hhx ", c);
+ line[cols] = isprint(c) ? c : '.';
+
cols++;
bytes++;
}
+
+ // Fill the rest of the hex space with spaces
+ for(cols; cols < line_width; cols++) printf(" ");
+
+ printf(" >%s<", line);
+
rainbow(freq, bytes);
- printf("\n%08x\n", bytes);
+ printf("\n%06x\n", bytes);
return 0;
}