Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Char array to Long in C

Tags:

c

memory

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.

like image 648
AjayR Avatar asked Jul 14 '11 01:07

AjayR


People also ask

Can char be converted to long?

When you cast each char back to a long , you are actually getting the ASCII value of each character in the string. So the char '1' is actually represented in memory as an integer 49, '2' is '50', and so on. What you will need to do is convert the string as a whole back to the integer representation.

How do you convert a number to a character array?

Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number. Separating integer into digits and accommodate it to a character array.

Can you convert string to char in C?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').


2 Answers

You can do:

union {
 unsigned char c[4];
 long l;
} conv;

conv.l = 0xABC;

and access c[0] c[1] c[2] c[3]. This is good as it wastes no memory and is very fast because there is no shifting or any assignment besides the initial one and it works both ways.

like image 92
Vinicius Kamakura Avatar answered Oct 05 '22 11:10

Vinicius Kamakura


Leaving the burden of matching the endianness with your other function to you, here's one way:

unsigned long int l = pdest[0] | (pdest[1] << 8) | (pdest[2] << 16) | (pdest[3] << 24);

Just to be safe, here's the corresponding other direction:

unsigned char pdest[4];
unsigned long int l;
pdest[0] = l         & 0xFF;
pdest[1] = (l >>  8) & 0xFF;
pdest[2] = (l >> 16) & 0xFF;
pdest[3] = (l >> 24) & 0xFF;

Going from char[4] to long and back is entirely reversible; going from long to char[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 pdest from left to right.)

Addendum: I'm also assuming that CHAR_BIT == 8. In general, substitute multiples of 8 by multiples of CHAR_BIT in the code.

like image 31
Kerrek SB Avatar answered Oct 05 '22 12:10

Kerrek SB