0

I have a variable s of type size_t and a variable buffer of type unsigned char. I wish to save this variable in buffer in network order as 4 bytes. How can I do it?

MaMu
  • 1,837
  • 4
  • 20
  • 36
  • 1
    Are you sure `size_t` if four bytes wide on your system? – alk Feb 12 '14 at 11:31
  • It is 64-bit system.. How can I check how wide is size_t? I can also save it as `uint32_t` or any type, which will be better for this purpose. `uint32_t` is 4 bytes on 64-bit system, isn't it? – MaMu Feb 12 '14 at 11:33
  • 2
    On a 64bit system I'd expect `sizeof(size_t)` to return 8. – alk Feb 12 '14 at 11:35
  • 1
    `uint32_t` shall be 32bits wide for any implementation. – alk Feb 12 '14 at 11:49

2 Answers2

2
size_t myvar;

myvar = htonl(myvar); // For the endian issues

memcpy(buffer, &myvar, sizeof(size_t));
alk
  • 69,737
  • 10
  • 105
  • 255
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
2
char c8[8] = {0};
size_t s = 0x1233456789abcdef0, s_be = 0;

if (4 == sizeof(s))
{
  s_be = htonl(s);
}
else if (8 == sizeof(s))
{
  s_be = htobe64(s);
}
else
{
  assert(0);
}

memcpy(c8, &s_be, sizeof(s_be));

For htobe64() have a look here: https://stackoverflow.com/a/4410728/694576

Community
  • 1
  • 1
alk
  • 69,737
  • 10
  • 105
  • 255