0

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.

kubiej21
  • 700
  • 4
  • 14
  • 29

2 Answers2

1

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

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
  • A specific order of bytes is not really necessary since I will be the only the referencing this data. I tried using memcpy, but it did not work as expected. For my test, number = 16; but upon printing the bytes, it returned with 10000000000000000000000000000000 – kubiej21 Feb 03 '13 at 02:54
  • The first byte is 0x10, which is 16 base 10. You are running on a machine that has the lest significant byte first (little endian). – Richard Schneider Feb 03 '13 at 02:57
  • Ahh okay. I was expecting the data to contain leading zeros... Thanks for the help. – kubiej21 Feb 03 '13 at 03:12
  • Is it possible to include leading zeros using memcpy? It just crossed my mind that I will not know the order of magnitude in this format. – kubiej21 Feb 03 '13 at 04:45
0

Try something like

*((uint32_t*)p) = number;
SecurityMatt
  • 6,593
  • 1
  • 22
  • 28