Monday, May 24, 2010

How can I make letters instead of numbers appear in base16 number in c++?

I'm doing a decimal to hexadecimal c++ program. However, instead of displaying A (or B or C or D or E or F), it displays 10 (or 11 or 12 or 13 or 14 or 15) instead. Here's the source code:





#include %26lt;iostream.h%26gt;


#include %26lt;math.h%26gt;


using namespace std;





int main ()


{


int input, i, j, k, result, power, hex_dig;


char hex_letter;





i = 1;


j = 0;


power = 0;





system ("cls");





cout %26lt;%26lt; "Enter an integer number [1-50]: ";


cin %26gt;%26gt; input;


k = i;


result = 0;


power = 0;


while (k %26gt; 0)


{


j = k % 16;


k = k / 16;





if (k %26lt; 10)


{


result = result + (pow(10,power) * j);


power = power + 1;


}


else if (k == 10)


{


hex_letter = 'A';


cout %26lt;%26lt; hex_letter %26lt;%26lt; j %26lt;%26lt; endl;


}


else if (k == 11)


{


hex_letter = 'B';


cout %26lt;%26lt; hex_letter %26lt;%26lt; j %26lt;%26lt; endl;


}


else if (k == 12)


{


hex_letter = 'C';


cout %26lt;%26lt; hex_letter %26lt;%26lt; j %26lt;%26lt; endl;


}


else if (k == 13)


{


hex_letter = 'D';

How can I make letters instead of numbers appear in base16 number in c++?
Store the k % 16 values of each iteration in a string of characters.


If (k %16) %26gt; 9, then 10 ≡ A ; 11 ≡ B ; 12 ≡ C ; 13 ≡ D ; E ≡ 14; F ≡ 15.


In the next step reverse that string using the function ' strrev() '.


That is your equivalent hexadecimal number
Reply:use C# -_-
Reply:I see that you read an integer into input, but I don't see where you do anything with that integer.





Why do you reinitialize hex_letter in each if else statement? Why not simply output the intended letter.





Or you could add 85 to each number, then 10 would equal 95, and 11 would equal 96, then cout the number without quotes and a letter will display. This would also eliminate all your if else statements.





95 in ASCII is capital A, 96 is B, etc.





You should also end your if else with an else, in the event none of the previous if else statements are entered.


No comments:

Post a Comment