How to assign long to character array and later extract it

J

Jens Thoms Toerring

How to assign long to character array and later extract it

Your question is a bit vague (you can't assign a long to a char
array), so I can just assume that you want to know how to store
the bits that make up a long in the elements of a char array
and later to retrieve the value - and that's rather simple to be
done using the memcpy() function:

#include <stdio.h>
#include <string.h>

int main( void )
{
long int a = 1234;
char c[ sizeof a ]; /* ok since sizeof is evaluated at compile time */

printf( "long variable is set to %ld\n", a );

/* Copy the long to the char array */
memcpy( c, &a, sizeof a );

/* Do something in between with the long */
a = -76543;
printf( "But now it's %ld\n", a );

/* Get the long back from where it's stored in the char array
and print it to demonstrate that it did work */
memcpy( &a, c, sizeof a );
printf( "And here it's %ld again\n", a );

return 0;
}
Regards, Jens
 
K

Keith Thompson

How to assign long to character array and later extract it

Please explain more clearly what you're trying to do. Do you want to
store a character string in decimal, a sequence of bytes, a sequence
of '0' and '1' characters representing bits, or what?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top