ro******@gmail.com wrote:
Hi,
How to assign long to character array and later extract it
#include <stdio.h>
#include <string.h>
#include <limits.h>
int main(void)
{
long lval = LONG_MAX / 2 + LONG_MAX / 4 + LONG_MAX / 8 + 1;
/* if you don't like it choose your own value */
long newval = 0;
unsigned char carray[sizeof lval];
size_t ndx;
printf
("The original long has a value of %ld, and its size is %lu\n",
lval, (unsigned long) sizeof lval);
memcpy(carray, &lval, sizeof lval);
printf("The character array contains these values:\n");
for (ndx = 0; ndx < sizeof lval; ndx++)
printf(" carray[%lu] = %u (%#o)\n", (unsigned long) ndx,
carray[ndx], carray[ndx]);
memcpy(&newval, carray, sizeof lval);
printf("The value of the reconstituted new long value is %ld\n",
newval);
return 0;
}
[output on one implementation]
The original long has a value of 1879048190, and its size is 4
The character array contains these values:
carray[0] = 254 (0376)
carray[1] = 255 (0377)
carray[2] = 255 (0377)
carray[3] = 111 (0157)
The value of the reconstituted new long value is 1879048190