Converting a 4 digit number into a BCD number?

Hi I'm having trouble converting a 4 digit number into a BCD number, in the program I did below I was able to convert a 2 digit number into BCD, but I do not know how to convert a 4 digit number or how to start it.

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
string asciiNum;

char digMost, digLeast;
int packBCD, intBCD;
cout << "Enter a two-digit number : " ;
cin >> asciiNum;

printf("\n\nMost sig. ascii digit = %x Least sig. ascii digit = %x\n\n", asciiNum[0], asciiNum[1]);
digMost = asciiNum[0] & 0x0f;
digLeast = asciiNum[1] & 0x0f;

printf("Most sig. bcd digit = %x Least sig. bcd digit = %x\n\n", digMost, digLeast);
packBCD = 0;
packBCD = packBCD | digMost;
packBCD = packBCD << 4;
packBCD = packBCD | digLeast;
intBCD = packBCD;
printf("Packed BCD value = %x \n\n", packBCD);
printf("int BCD = %d\n\n", intBCD);

system("PAUSE");
return EXIT_SUCCESS;
}
Please use code tags when posting code.

To convert an ascii character to it's numeric value, I think it's clearer to do ch - '0' rather than ch & 0x0f, but to each his own.

Okay, if you have a number is ascii form in asciiNum, you can convert to bcd with a simple loop:
1
2
3
4
unsigned packBCD=0;
for (int i=0; i<asciiNum.size(); ++i) {
    packBCD = (packBCD<<4) | (asciiNum[i] - '0');
}


I'm sorry that I did not use the code tags when in my previous post it I forgot to format it before posting.

I revised my program with the loop from what I had and it worked out. I did not think of using a loop.

Thank You!
Topic archived. No new replies allowed.