Skip to content

Commit 361e92a

Browse files
feat: rewrite decmial_to_hexadecimal and make it testable
1 parent 923635f commit 361e92a

File tree

1 file changed

+34
-20
lines changed

1 file changed

+34
-20
lines changed

others/decimal_to_hexadecimal.cpp

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,46 @@
33
* @brief Convert decimal number to hexadecimal representation
44
*/
55

6-
#include <iostream>
6+
#include <cassert>
7+
#include <cstdint>
8+
#include <string>
9+
#include <vector>
710

811
/**
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
1017
*/
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";
2123

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;
2627
}
27-
hexArray[i] = valueToConvert; // Gets last value
28+
while (i >= 0) ret.push_back(HexValues[i--]);
29+
return ret;
30+
}
2831

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+
}
3141

32-
std::cout << std::endl;
42+
/**
43+
* Main program
44+
*/
45+
int main(void) {
46+
tests(); // run self test imlementation
3347
return 0;
3448
}

0 commit comments

Comments
 (0)