This question may looks silly, but please guide me
I have a function to convert long data to char array
void ConvertLongToChar(char *pSrc, char *pDest)
{
pDest[0] = pSrc[0];
pDest[1] = pSrc[1];
pDest[2] = pSrc[2];
pDest[3] = pSrc[3];
}
And I call the above function like this
long lTemp = (long) (fRxPower * 1000);
ConvertLongToChar ((char *)&lTemp, pBuffer);
Which works fine.
I need a similar function to reverse the procedure. Convert char array to long.
I cannot use atol or similar functions.
Leaving the burden of matching the endianness with your other function to you, here’s one way:
Just to be safe, here’s the corresponding other direction:
Going from
char[4]to long and back is entirely reversible; going from long tochar[4]and back is reversible for values up to 2^32-1.Note that all this is only well-defined for unsigned types.
(My example is little endian if you read
pdestfrom left to right.)Addendum: I’m also assuming that
CHAR_BIT == 8. In general, substitute multiples of 8 by multiples ofCHAR_BITin the code.