Reputation:
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;
}
Upvotes: 0
Views: 2196
Reputation: 108978
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);
Upvotes: 1
Reputation: 4808
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
Upvotes: 6
Reputation: 49803
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
.
Upvotes: 2