Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

hex it!: Write a utility program tthat reads a positive integer and prints out a

ID: 3657887 • Letter: H

Question

hex it!: Write a utility program tthat reads a positive integer and prints out a hexadecimal string representation of it. You must include in your program two functions. hexdigit: receives an integer argument in the range of 0 through 15 and returns a string containing the equivalent hexadecimal digit: "0", "1", "2", "3", ..., "9", "a", "b", "c", "d", "e", "f". hexnumeral: receives a non-negative integer argument and returns a string containing the equivalent hexadecimal numeral. The program basically reads in an integer (non-negative) and prints out its hex representation using hexnumeral (which in turn uses hexdigit).

Explanation / Answer

char hexdigit(int value)
{
// @assume 0 <= value < 16
if(value < 10)
return (char)('0'+value);
else
return (char)('a'+value);
}

string hexnumeral(int decimal)
{
string output = "";

while(decimal > 0)
{
output = hexdigit(decimal%16) + output;
decimal = decimal/16;
}

return output;
}