Hello all, I'm trying to modify some code but I'm having some difficulty - probably because I don't really understand the function in the first place. Its one my supervisor found online that seemed to work fine for the purposes of our test code. However; after some poking around its not working entirely as I need it to, so I was going to modify it. Only to find I really have no idea how to modify it to accomplish what I need.
Here's the downloaded function:
////////////////////////////////////////////////////////////////////////////////
// FUNCTION : atobcd
// ARGUMENTS: pBcd - (output) void pointer to location where the encoded
// text number will be written.
// nBcdLen - (input) usable length of the pBcd variable.
// pszNumber - (input) pointer to a char array containing the text
// representation of the number to encode.
// nNumLen - (input) length of the input pszNumber char array.
// RETURNS : 0 - Success
// !0 - Error
// PURPOSE : Converts an ASCII (text) representation of a number to BCD.
// (Binary Coded Decimal)
////////////////////////////////////////////////////////////////////////////////
int CTestDPDlg::atobcd(void* pBcd, int nBcdLen, char* pszNumber, int nNumLen)
{
int nError = 0;
int i = 0; //INDEX TO INPUT ASCII REPRESENTATION OF THE NUMBER
int j = 0; //INDEX TO BCD REPRESENTATION OF THE NUMBER
char szSingleNumberAscii[2] = {0};
char nSingleNumberBinary = 0;
char* pBcdVal = reinterpret_cast<char*>(pBcd);
//LOOP UNTIL END OF ASCII NUMBER OR END OF BCD REACHED
while(i < nNumLen && j < nBcdLen)
{
memset(szSingleNumberAscii, 0, sizeof(szSingleNumberAscii));
nSingleNumberBinary = 0;
szSingleNumberAscii[0] = pszNumber[i];
nSingleNumberBinary = atoi(szSingleNumberAscii);
if(!(i%2))
{
pBcdVal[j] = nSingleNumberBinary << 4;
}
else
{
pBcdVal[j] += nSingleNumberBinary;
j++; //INCREMENT EVERY OTHER ITERATION OF THE LOOP
}
i++; //INCREMENT EVERY ITERATION OF THE LOOP
}
return nError;
}
And we're using it in this fashion:
value.Remove('.');
atobcd(positionSSBL->zPosRawByteArray, 3, value.GetBuffer(), value.GetLength());
if zPosRaw = 1234.5 the array looks like this:
zPosRawByteArray[0] = 0x12
zPosRawByteArray[1] = 0x34
zPosRawByteArray[2] = 0x50
and what I need is:
zPosRawByteArray[0] = 0x01
zPosRawByteArray[1] = 0x23
zPosRawByteArray[2] = 0x45
The digit in the tens position needs to be the LSB. I think its just a matter of changing the atobcd so it goes backwards? But I'm afraid I'm so new to C++ that I'm not really grasping the function properly, even stepping through it I find its hard to really understand what's happening.