l Wawa
l Wawa

Reputation: 43

Does converting an int into a hex always results in a different number?

I was asked to write a code that converts an integer and turns it into a hex. I managed to write the code. However, every time I enter the same number I always get a new hex value, is this normal?

Also, why the values are different from expected? for example, if I enter "1" isn't the hex value supposed to be "01"?

The value that I get is something like "95f9a4".

#include <stdio.h>
#include <string.h>
int main(void)
{
    int i;
    char str[5] = { "\0" };
    printf("Please enter a num:");
    scanf_s("%d", &i);
    sprintf_s(str, "%x", i);
    printf_s("%x", str);
}

Upvotes: 0

Views: 97

Answers (1)

Amadan
Amadan

Reputation: 198324

You have unnecessary code, which resulted in more places to make a mistake.

After sprintf_s(str, "%x", i), str contains the hex representation of i. Then printf_s("%x", str); prints out the str pointer as a hex number.

The minimal fix is to change the latter line to printf_s("%s", str) to output the content of the string str.

The better way would be to just directly print out the hex value, without going through str at all. Replace both lines with just printf_s("%x", i).

Upvotes: 4

Related Questions