我有s
类型的变量size_t
和buffer
类型的变量unsigned char
。我希望将此变量保存在buffer
网络顺序为4个字节。
我该怎么办?
答案 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