-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver.c
134 lines (117 loc) · 2.45 KB
/
driver.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#define ArrayCount(x) (sizeof((x))/sizeof((x)[0]))
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
typedef uint32_t u32;
typedef uint64_t u64;
typedef struct entire_file
{
u32 size;
char *buf;
} entire_file;
union bits32 { u32 i; float f; };
union bits64 { u64 i; double f; };
static entire_file ReadEntireFile(char *path)
{
entire_file result = {0};
FILE *file = fopen(path, "rb");
if (file)
{
fseek(file, 0, SEEK_END);
result.size = ftell(file);
fseek(file, 0, SEEK_SET);
if (result.size)
{
result.buf = malloc(result.size);
if (result.buf)
{
size_t rb = fread(result.buf, 1, result.size, file);
if (rb != result.size)
{
fprintf(stderr, "Error: short read %lu/%u\n", rb, result.size);
free(result.buf);
result.buf = 0;
}
}
else
{
fprintf(stderr, "Error: unable to allocate %u bytes\n", result.size);
result.size = 0;
}
}
}
else
{
fprintf(stderr, "Error: unable to open '%s'\n", path);
}
return result;
}
#if 0
static void FreeEntireFile(entire_file *file)
{
if (file->buf)
{
free(file->buf);
file->buf = 0;
}
file->size = 0;
}
#endif
int main(int argc, char **argv)
{
if (argc != 4)
{
fprintf(stderr, "Usage: %s <input> <float|double> <output>\n", argv[0]);
return 1;
}
char *path = argv[1];
char *floatType = argv[2];
char *outputPath = argv[3];
bool outputAsF32 = true;
if (strcmp(floatType, "double") == 0)
{
outputAsF32 = false;
}
else if (strcmp(floatType, "float") != 0)
{
fprintf(stderr, "Error: invalid float type '%s'\n", floatType);
return 1;
}
entire_file file = ReadEntireFile(path);
if (!file.size)
return 1;
FILE *out = fopen(outputPath, "w+");
if (!out)
{
fprintf(stderr, "Error: unable to open '%s' for writing\n", outputPath);
return 1;
}
float *digits = (float *)file.buf;
u32 digitCount = file.size / sizeof(u32);
if (outputAsF32)
{
for (u32 i = 0; i < digitCount; ++i)
{
union bits32 cvt = {.f = digits[i]};
fprintf(out, "%u", cvt.i);
if (i + 1 < digitCount)
fprintf(out, ", ");
}
}
else
{
for (u32 i = 0; i < digitCount; ++i)
{
union bits64 cvt = {.f = (double)digits[i]};
fprintf(out, "%lu", cvt.i);
if (i + 1 < digitCount)
fprintf(out, ", ");
}
}
fclose(out);
//FreeEntireFile(&file);
return 0;
}