A 32-bit integer can be represented as an array of 4 chars,
assuming 8 bits per byte. Conversion between ordinary
integers and this array can be done by bitwise
mask-and-shift operations. The following should work for any
unsigned integer type >= 32 bits; I've used long long here:
#include <stdio.h>
#include <limits.h>
int main(void)
{
unsigned long long i = 1234567890;
unsigned char c[4];
printf("Your integers are %i bits\n", CHAR_BIT *
sizeof(i));
c[0] = i & 0xff; /* least significant byte */
c[1] = (i & 0xff00) >> 8;
c[2] = (i & 0xff0000) >> 16;
c[3] = (i & 0xff000000) >> 24;
printf("0x%08x == ", i);
printf("0x%02x%02x%02x%02x", c[3], c[2], c[1], c[0]);
return 0;
}
On my Win32 system this prints
Your integers are 64 bits
0x499602d2 == 0x499602d2
The first hex value is derived from i, the second from c[],
and they should be the same. I don't have a 64-bit machine
to try this on; maybe someone who has would oblige!
(To write binary data from c[] you'd need a different format
string of course.)
There are also considerations of endianess to be taken into
account.
David