I have an int that I need to store as two chars.

So is there some way to get the first 8 bits and the second 8 bits and store them as chars.

And if so, how would I recombine them later to get a meaningful int value?

what makes you think an int is only 16 bits? Depending on your compiler, it might, but then again it might not.

what makes you think an int is only 16 bits? Depending on your compiler, it might, but then again it might not.

Okay, then store an int as however many chars it needs to be...that's easily determinable using sizeof

char buf[sizeof(int)];
int x = 1234;
memcpy(buf, &x, sizeof(int));

This might also work: *(int *)buf = x;

char buf[sizeof(int)];
int x = 1234;
memcpy(buf, &x, sizeof(int));

Okay...how do I get from buf to the original int?

reverse the order of the first two parameters to memcpy(). Or x = *(int*)buf;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.