Вопрос

I have a void pointer that I would like to store the binary value of a long at. For example:

void * p;
long number;

p = malloc(16);
p = memset(p, 0, 16);
number = 15;

/* PRINTS FIRST 16 BYTES */
for(i = 0; i < memSize; i++)
     printf("%02x", ((unsigned char *) p) [i]);
printf("\n");

Above code will print

00000000000000000000000000000000

I would like to set the first 8 bytes to the value of "number", for example:

000000000000000F0000000000000000

Is there a simple way of doing this? I suppose bit shifting would work, but that could become quite tedious.

Это было полезно?

Решение

Why not use memcpy?

 memcpy (p, &number, sizeof(number));

Do you care about the order of bytes (most significant vs least significant first)? Perhaps you should read http://en.wikipedia.org/wiki/Endianness

Другие советы

Try something like

*((uint32_t*)p) = number;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top