You are not actually allocating any memory for your string
, so using d[j]
is undefined behavior. You need to use d += ...
or d.push_back(...)
instead.
But even if you fix that error, your code still won't work correctly. It is not outputting any string value at all for a=0
when it should be returning "0"
. And it returns other strings in reverse order. For example, a=16
is returning "01"
instead of "10"
, a=31
is returning "F1"
instead of "1F"
, a=32
is returning "02"
instead of "20"
, etc.
Try something more like this instead:
#include <string>
std::string DecToHex(int a)
{
int i;
std::string d;
d.reserve(sizeof(a)*2);
do
{
i = a % 16;
if ((i >= 10) && (i <= 15))
d.insert(0, 1, 'A'+(i-10));
else
d.insert(0, 1, '0'+i);
a /= 16;
}
while (a != 0);
return d;
}
Or:
#include <string>
#include <algorithm>
std::string DecToHex(int a)
{
int i;
std::string d;
d.reserve(sizeof(a)*2);
do
{
i = a % 16;
if ((i >= 10) && (i <= 15))
d += ('A'+(i-10));
else
d += ('0'+i);
a /= 16;
}
while (a != 0);
std::reverse(d.begin(), d.end());
return d;
}
Or:
#include <string>
#include <sstream>
#include <algorithm>
std::string DecToHex(int a)
{
int i;
std::ostringstream oss;
do
{
i = a % 16;
if ((i >= 10) && (i <= 15))
oss << ('A'+(i-10));
else
oss << ('0'+i);
a /= 16;
}
while (a != 0);
std::string d = oss.str();
std::reverse(d.begin(), d.end());
return d;
}
In any case, your function is not handling negative numbers at all, which requires some extra work (switching to 2s complement representation before then calculating the hex). I'll leave that as an exercise for you to work out.