Hi everyone. Im trying to make decimal to hexadecimal converter. The code is given below:

 ``1234567891011121314151617181920212223242526272829303132333435363738`` `````` #include #include using namespace std; void hexadecimal(int x); int main() { int num; cout<<"Enter a number"<>num; hexadecimal(num); system("pause"); return 0; } void hexadecimal(int x) { int rem, qou; string hex[10]; for(int i=0 ; i<10 ; i++) hex[i] = "\n"; qou = x/16; cout<

i know im doing it wrong. can anyone help me to do it right.And at line 33 and 35 != and << operators are also not working. can anyone here explain???
try this. haven't tested it.

 ``12345678910111213141516171819`` ``````void hexadecimal(int x) { string hex[10]; int index = 0; // position to insert in hex do { rem = x%16; if (rem > 9) hex[index] = 'A' + rem - 10; else hex[index] = '0' + rem; index++; x /= 16; } while (x); for(int i=index-1 ; i>=0 ; i--) { cout << hex[i]; } cout << endl; }``````

EDIT: Bit operations would be more efficient.
instead of `rem = x % 16;` you can do `rem = x & 15;`
instead of ` x /= 16; ` you can do ` x >> 4; `
Last edited on
at line 16 insertion operator is not working....
You don't need an array of strings. Use either a single string, or an array of characters.
`char hex[10];`
Two approaches:

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950`` ``````#include #include #include #include std::string as_hex( unsigned value ) { const char* digits = "0123456789ABCDEF" ; std::string num("0x") ; unsigned hexDigits = std::numeric_limits::digits / 4 ; unsigned i=0; unsigned byteMask = 0xF << (hexDigits-1)*4 ; // skip leading 0's while ( i < hexDigits && (byteMask & value) == 0 ) { byteMask >>= 4 ; ++i ; } while ( i < hexDigits ) { unsigned digit = (byteMask & value) >> 4*(hexDigits-i-1) ; num += digits[digit] ; byteMask >>= 4 ; ++i ; } if ( num.length() == 2 ) num += '0' ; return num ; } int main() { int num ; std::cout << "Enter a number: " ; std::cin >> num ; std::cout << std::showbase ; std::cout << num << " is " << std::hex << num << '\n' ; std::cout << std::dec << num << " is " << as_hex(num) << '\n' ; }``````
Topic archived. No new replies allowed.