简体   繁体   中英

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);
}

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM