forked from teamrudra/R24-Test-Hex-Editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.c
111 lines (93 loc) · 2.43 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "utils.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void print_help(char* target)
{
printf("Hex Editor\n");
printf("Usage: %s [-m2h] [input]\n\n", target);
printf("Arguments:\n");
printf("================================================\n");
printf(" -h | --help : Print this message\n");
printf(" -b2h | --binary_to_hex : Mode to dump hex\n");
printf(" -h2b | --hex_to_binary : Mode to save binary\n");
}
void error_infile(char* target)
{
fprintf(stderr, "Usage: %s [-m2h] [input]\n", target);
}
void error_infile_open()
{
fprintf(stderr, "Couldn't open the input file\n");
}
void print_pretty(char offset, int act_read_bytes, uint8_t* buffer, FILE* out_file)
{
// prints read bytes and hex in intuitive format
fprintf(out_file, "%016lld ", offset);
for (int i = 0; i < LEN_LINE; i++)
{
if (i < act_read_bytes)
{
fprintf(out_file, " %02X", buffer[i]);
}
else{
fprintf(out_file, " ");
}
}
fprintf(out_file, " |");
for (int i = 0; i < act_read_bytes; i++)
{
if (buffer[i] > 31 && buffer[i] < 127)
fprintf(out_file, "%c", buffer[i]);
else fprintf(out_file, ".");
}
fprintf(out_file, "|\n");
};
void bin2hex(FILE* in_file, FILE* out_file)
{
// allocate approriate memory for buffer
uint8_t* buffer = (uint8_t*)malloc(LEN_LINE);
int offset = 0x0000000000000001;
while(!feof(in_file))
{
int read_bytes = LEN_LINE;
int act_read_bytes = fread(buffer, sizeof(uint8_t), read_bytes, in_file);
if (act_read_bytes > 0)
{
print_pretty(offset, act_read_bytes, buffer, out_file);
offset += act_read_bytes;
}
else break;
}
free(buffer);
}
void hex2bin(FILE* in_file, FILE* out_file)
{
int count = 0;
char curr_char, curr_char_value, curr_byte=0;
fseek(in_file, OFFSET, SEEK_CUR);
while (!feof(in_file))
{
int n = fread(&curr_char, sizeof(char), 1, in_file);
if (n == 0) break;
if (curr_char == '\n')
{
fseek(in_file, OFFSET, SEEK_CUR);
}
else if (curr_char == '|')
{
fseek(in_file, 16+1, SEEK_CUR);
continue;
}
else if (curr_char >= '0' && curr_char <= '9')
curr_char_value = curr_char - '0';
else if (curr_char >= 'A' && curr_char <= 'F')
curr_char_value = curr_char - 'A' + 0xa;
else continue;
curr_byte = (curr_byte << 2) + curr_char_value;
if (count)
fprintf(out_file, "%c", curr_byte);
count = count+1;
count = count%2;
}
}