将size_t保存为无符号字节

时间:2014-02-12 11:28:38

标签: c

我有s类型的变量size_tbuffer类型的变量unsigned char。我希望将此变量保存在buffer网络顺序为4个字节。 我该怎么办?

2 个答案:

答案 0 :(得分:2)

size_t myvar;

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

memcpy(buffer, &myvar, sizeof(size_t));

答案 1 :(得分: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));

htobe64()请点击此处:https://stackoverflow.com/a/4410728/694576