|
3 | 3 | * @brief Convert decimal number to hexadecimal representation
|
4 | 4 | */
|
5 | 5 |
|
6 |
| -#include <iostream> |
| 6 | +#include <cassert> |
| 7 | +#include <cstdint> |
| 8 | +#include <string> |
| 9 | +#include <vector> |
7 | 10 |
|
8 | 11 | /**
|
9 |
| - * Main program |
| 12 | + * @brief converts a given decimal integer value to its equavalent hexadecimal |
| 13 | + * string |
| 14 | + * |
| 15 | + * @param value the value to be converted |
| 16 | + * @return std::string the hexadecimal string |
10 | 17 | */
|
11 |
| -int main(void) { |
12 |
| - int valueToConvert = 0; // Holds user input |
13 |
| - int hexArray[8]; // Contains hex values backwards |
14 |
| - int i = 0; // counter |
15 |
| - char HexValues[] = "0123456789ABCDEF"; |
16 |
| - |
17 |
| - std::cout << "Enter a Decimal Value" |
18 |
| - << std::endl; // Displays request to stdout |
19 |
| - std::cin >> |
20 |
| - valueToConvert; // Stores value into valueToConvert via user input |
| 18 | +std::string decimal_to_hexadecimal(std::uint32_t value) { |
| 19 | + std::vector<uint32_t> hexArray{}; |
| 20 | + std::string ret = ""; |
| 21 | + size_t i = 0; |
| 22 | + const char HexValues[] = "0123456789ABCDEF"; |
21 | 23 |
|
22 |
| - while (valueToConvert > 15) { // Dec to Hex Algorithm |
23 |
| - hexArray[i++] = valueToConvert % 16; // Gets remainder |
24 |
| - valueToConvert /= 16; |
25 |
| - // valueToConvert >>= 4; // This will divide by 2^4=16 and is faster |
| 24 | + while (value > 15) { |
| 25 | + hexArray.at(i++) = value % 16; |
| 26 | + value /= 16; |
26 | 27 | }
|
27 |
| - hexArray[i] = valueToConvert; // Gets last value |
| 28 | + while (i >= 0) ret.push_back(HexValues[i--]); |
| 29 | + return ret; |
| 30 | +} |
28 | 31 |
|
29 |
| - std::cout << "Hex Value: "; |
30 |
| - while (i >= 0) std::cout << HexValues[hexArray[i--]]; |
| 32 | +/** |
| 33 | + * @brief self test implementation |
| 34 | + * @returns void |
| 35 | + */ |
| 36 | +static void tests() { |
| 37 | + assert(decimal_to_hexadecimal(0) == "0"); |
| 38 | + assert(decimal_to_hexadecimal(1) == "1"); |
| 39 | + assert(decimal_to_hexadecimal(10) == "A"); |
| 40 | +} |
31 | 41 |
|
32 |
| - std::cout << std::endl; |
| 42 | +/** |
| 43 | + * Main program |
| 44 | + */ |
| 45 | +int main(void) { |
| 46 | + tests(); // run self test imlementation |
33 | 47 | return 0;
|
34 | 48 | }
|
0 commit comments