0

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;
}
  • Do you know about [`strtol`](https://msdn.microsoft.com/en-us/library/w4z2wdyc.aspx)? – Weather Vane Nov 23 '16 at 21:22
  • If @WeatherVane's comment doesn't help you, please include a Minimal Complete Verifiable Example (http://stackoverflow.com/help/mcve) including the hint, what exactly you do expect from the code. – Bodo Thiesen Nov 23 '16 at 21:25
  • 1
    To convert from decimal to BCD, start with zero result and multiplier 1. In a loop, divide the decimal value by ten, but take the remainder first. Multiply the remainder with the multiplier, and add to result. Multiply multiplier by 16. Repeat loop as long as the decimal value is greater than zero. To convert from BCD to decimal, you do the same, except you divide the BCD value by 16, and multiply the multiplier by 10. – Nominal Animal Nov 23 '16 at 21:56
  • 1
    http://stackoverflow.com/questions/1408361/unsigned-integer-to-bcd-conversion – M.M Nov 23 '16 at 22:02
  • 1
    @M.M your link helps :) Thank you so much. –  Nov 23 '16 at 22:36

3 Answers3

6
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
Tibor Takács
  • 3,535
  • 1
  • 20
  • 23
2

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.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • 1
    The code is meant to convert 0x based numbers, For example, BCD(0x1991) which will give you the answer of 6545 . However, I have no clue how to convert 1991 to 0x1991 –  Nov 23 '16 at 21:25
  • 1
    @xTiraMissU: That's not what you asked, even if it is what you meant to ask. Regardless, what I wrote still applies. – Scott Hunter Nov 23 '16 at 23:18
  • 1
    Thanks. I already fixed that :) Thank you for correcting my mistakes –  Nov 24 '16 at 00:54
1

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);
pmg
  • 106,608
  • 13
  • 126
  • 198