hexdump: Add canonical output (like -C flag)

This commit is contained in:
g1n 2021-08-23 11:21:38 +03:00
parent d5fb5de386
commit bd80c5a1e4
2 changed files with 33 additions and 12 deletions

View File

@ -1,45 +1,64 @@
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int curgroup = 0; // To know where 8 group
int dumpgroup = 0; // To know where newline should be
int hexnum = 1; // To put space after every second hex number
bool canonical = true; // -C flag
int chardump(char *data, int end_of_line /* to display only 16 chars */) {
int chardump(char *data, int start_of_line, int end_of_line /* to display only 16 chars */) {
for (int i=0; i < end_of_line; i++) {
if (data[i] == "\0")
if (data[i] == "\0" || data[i] == ' ')
printf(".");
else
printf("%c", data[i]);
}
printf("\n");
return 0;
}
int hexdump(char *data) {
//printf("%s\n", data); // FIXME
int cur_start_of_line = 0;
for (int i=0; i < strlen(data); i++) {
hexnum++;
if (data[i] == '\0')
printf("00");
else
printf("%02x", data[i]);
if (hexnum%2) {
printf(" ");
else {
if (!canonical)
printf("%02x", data[i]);
else {
printf("%02x ", data[i]);
//dumpgroup++;
}
}
if (hexnum%2 && hexnum >= 2) {
if (!canonical)
printf(" ");
curgroup++;
}
if (curgroup == 4) {
if (canonical) {
printf(" ");
}
curgroup = 0;
dumpgroup++;
}
if (dumpgroup == 8) {
if (dumpgroup == 2) {
dumpgroup = 0;
printf(" ");
chardump(data, i);
//printf("\n");
// printf("|");
// chardump(data, cur_start_of_line, hexnum);
// printf("|");
// cur_start_of_line = i;
printf("\n");
}
}
//printf("\n"); // FIXME
}
int main() {
FILE *infile = fopen("../tests/test.bin", "r");//fopen("test.bin", "r");
FILE *infile = fopen("../tests/test2.bin", "r");//fopen("test.bin", "r");
char data[50];
while (fgets(data, 50, infile) != NULL) {
hexdump(data);

2
tests/test2.bin Normal file
View File

@ -0,0 +1,2 @@
test TEST
test? 123 123