-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-misc.cc
98 lines (86 loc) · 1.92 KB
/
02-misc.cc
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
//
// Program
// Map a value of one range to another range.
// https://stackoverflow.com/a/5732390 is having a good
// explanation. Formula to be used:
// double slope = 1.0 * (output_end - output_start) / (input_end - input_start)
// output = output_start + slope * (input - input_start)
//
// Compile
// g++ -Wall -Wextra -std=c++17 -o 02-misc 02-misc.cc
//
// Execution
// ./02-misc
//
#include <iostream>
template<typename T>
struct Range {
T start;
T end;
};
struct Ranges {
Range<int> input;
Range<float> output;
};
double getSlope(const Ranges& ranges) {
return 1.0f *
(ranges.output.end - ranges.output.start) /
(ranges.input.end - ranges.input.start);
}
double map(const Ranges& ranges, int input) {
return (ranges.output.start + getSlope(ranges) *
(input - ranges.input.start));
}
//
// Entry function
//
int main() {
std::cout << "--- Map values b/w two ranges ---" << '\n';
std::cout << "--- Map -128 <> 127 to 0.0f <> 1.0f ---\n";
{
const Ranges s8 = {
.input = { .start = -128, .end = 127 },
.output = { .start = 0.0f, .end = 1.0f },
};
for (int idx = -128; idx <= 127; ++idx) {
printf("%4d, %lf\n", idx, map(s8, idx));
}
}
std::cout << "--- Map 0 <> 255 to 0.0f <> 1.0f ---\n";
{
const Ranges u8 = {
.input = { .start = 0, .end = 255 },
.output = { .start = 0.0f, .end = 1.0f },
};
for (int idx = 0; idx <= 255; ++idx) {
printf("%4d, %lf\n", idx, map(u8, idx));
}
}
return 0;
}
// Output
// --- Map values b/w two ranges ---
// --- Map -128 <> 127 to 0.0f <> 1.0f ---
// -128, 0.000000
// -127, 0.003922
// -126, 0.007843
// ...
// ...
// 0, 0.501961
// ...
// ...
// 125, 0.992157
// 126, 0.996078
// 127, 1.000000
// --- Map 0 <> 255 to 0.0f <> 1.0f ---
// 0, 0.000000
// 1, 0.003922
// 2, 0.007843
// ...
// ...
// 130, 0.509804
// ...
// ...
// 253, 0.992157
// 254, 0.996078
// 255, 1.000000