This is wrong:
char out[2];
sprintf(out, "%x", num); // to hex
because you write beyond the bounds of the array. Your number has two hexadecimal places, and you need an additional byte for the \0
terminator of the string. It has to be at least char out[3]
.
This is even wronger:
for(int i=0;i<2;i++)
printf("%x\n", out[i]);
You already have a hexadecimal string representation of the number and now take the individual characters and interpret them as hexadecimal numbers. Just output your out
string instead, e.g. puts(out)
or printf("%s\n", out)
(requires the \0
terminator to be present).
You can condense the whole thing to just
int main(void)
{
char *input = "78";
long num = strtol(input, NULL, 10); // to int
printf("%lx\n", num); // to hex
}
(note that strtol()
returns long
-- with larger numbers you'd get a problem converting this to int
.)