For pointers, it is better to use type unsigned long
(or unsigned long long
). Unless there is uintptr_t
data type.
Why unsigned
? Because shift operations are common only for unsigned integers. For signed ones, it is platform-dependent.
So it you want to transfer the address (for whatever reason, as address is usually process-local), you can do like the following:
/**
* @param ptr Pointer to serialize
* @param buf Destination buffer
* @param be If 0 - little endian, 1 - big endian encoding
*/
void ptr2buf(const void *ptr, void *buf, int be)
{
uintptr_t u = (uintptr_t)ptr;
unsigned char *d = buf;
if (be)
{
/* big endian */
d += sizeof(t) - 1;
for (i = 0; i < sizeof(t); ++i)
{
*d-- = u & 0xFF;
u >>= 8;
}
}
else
{
/* little endian */
for (i = 0; i < sizeof(t); ++i)
{
*d++ = u & 0xFF;
u >>= 8;
}
}
}