Code in C++ 1) Write a recursive function that converts an int to a hex string.
ID: 3586680 • Letter: C
Question
Code in C++
1) Write a recursive function that converts an int to a hex string. To convert an int to a hex, first mod the number by 16. Take the remainder and convert it to a hex equivalent (so 10=’A’, 11=’B’, 12=’C’, etc.) Then divide the int by 16 and repeat the process with the result.
So, for example, to convert 590 to hex,
590 %16 = 14 (so ‘E’). 590/16 = 36
2) Create a class declaration for a hex number. The class should consist of 2 private fields – an integer (for the integer version of the number) and a string (for the hex version of the number). The class declaration should also have (public methods and constructors): a constructor that takes as input an int, and a separate constructor that takes as input a string. It should also have 2 methods, one for converting an int to its corresponding hex number (in the form of a string) and a method that converts the string to its corresponding integer. It should also have getters and setters for the 2 fields. Now write the corresponding .cpp file. Note that the constructors and the setters should call the appropriate method so that the int field and the hex field always match up.
In your main, create at least 6 different hexnum objects. Make sure you test with different hex and integers.
36%16 = 4 36/16=2
2%16 = 2, 2/16 = 0
So the resulting hex number (in the form of a string) would be 24E
(if you need it, you can use a helper function).
Explanation / Answer
recursive function that converts an int to a hex string
//receives integer and string
string convertDecToHex(int decimalNumber, string buffer)
{
int x = decimalNumber % 16; //Takes the remainder
char x_to_char = x + '0';
if (decimalNumber == 0)
{
return buffer;
}
//To convert it to a hex equivalent
switch (x)
{
case 10: buffer = 'A' + buffer; break;
case 11: buffer = 'B' + buffer; break;
case 12: buffer = 'C' + buffer; break;
case 13: buffer = 'D' + buffer; break;
case 14: buffer = 'E' + buffer; break;
case 15: buffer = 'F' + buffer; break;
default: buffer = x_to_char + buffer;
}
return convertDecToHex(decimalNumber / 16, buffer);
}