### Help me convert decimal number to hexadecimal using string

I've a decimal number contained in a string and need to convert it to a hexadecimal number(as a string) without the use of `atoi()` or `atol()`
Last edited on
One possible solution is to use the sscanf function on the string containing your number, then use one of the thousands algorithms you can find googling on "decimal to hexadecimal conversion algorithm" (if this is the point of your exercise:) and, finally, using the sprintf function to do the conversion from number to string.
If you don't need to exercise on base number conversion, you can just use the %x or %X format specifier in the sprintf format and the magic is done.
Last edited on
Or use a pair of string streams:

 ``123456789101112`` ``````#include #include std::string to_hex( const std::string& decimal ) { unsigned long long number ; std::istringstream(decimal) >> number ; std::ostringstream stm ; stm << std::hex << std::showbase << number ; return stm.str() ; }``````
Right. Good point! But, what I forgot to ask to SameerThigale is if he is using C or C++.
As I have understood you may not use standard conversion functions. So all realizations showed above are wrong.
Thanks for those ideas people :) (:

What if I've a number with many digits, stored in a file(or string) and I don't want to convert it to number(intermediate)
It's possible convert between some bases, such as binary and hexadecimal, without converting to a number.

However, if you want to go from decimal to hexadecimal, the only sensible option is to convert it to an integer first.

The only other option I can think of would be to build a huge lookup table, where you search for the input string in the table, and retrieve the corresponding result. But if the input contains many digits, this suggestion is not feasible.
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263`` ``````int my_atoi(const string & strNum) { int nVal = 0; for (string::const_iterator it = strNum.begin(); it != strNum.end(); it++) { if (*it < '0' || *it > '9') return 0; nVal *= 10; nVal += (*it) - '0'; } return nVal; } char get_digit_char(unsigned char ucVal) { if (ucVal < 10) return '0' + ucVal; return 'A' + (ucVal-10); } string reverse_value(const string & strNum) { string strReversed; for (string::const_reverse_iterator it = strNum.rbegin(); it != strNum.rend(); it++) { strReversed += (*it); } return strReversed; } string dec_to_base(const string & strNum, unsigned char ucBase) { if (ucBase > 36) return "Base too Big"; int nVal = my_atoi(strNum); string strBaseVal; while (nVal) { unsigned char ucRem = nVal % ucBase; nVal /= ucBase; strBaseVal += get_digit_char(ucRem); } return reverse_value(strBaseVal); } int main() { string strNum = "12345"; cout << "dec_to_base: " << dec_to_base(strNum, 16) << endl; return 0; }``````