简体   繁体   中英

Converting an integer to 0x equivalent (Hex)

I have an integer input of 1991. How do I convert the input to 0x1991 instead of 7C7? I already wrote the code to convert the hex to decimal(the answer will be 6545)

int ui = 0x202;
int BCD(int value) //Converting 0xhex to decimal 
{
    int result = 0;
    result <<= 4;
    result |= ui % 10;
    ui /= 10;

    return value;
}
const int input = 1991;
int i = input;
int f = 1;
int result = 0x0;
while( i > 0 )
{
    int d = i % 10;
    result += d * f;
    f *= 16; 
    i /= 10;
}

printf("0x%x", result ); // 0x1991

You are using ui as the input and storing the result in result , but then returning value ; you should be using value as the input and returning result .

Build a string with the 0x prefix, then scan that.

int var, value = 1991;
char tmp[100];
sprintf(tmp, "0x%d", value);
if (sscanf(tmp, "%i", &var) != 1) /* error */;
printf("%d ==> %s ==> %d\n", value, tmp, var);

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