Reputation: 1869
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?
Upvotes: 0
Views: 263
Reputation: 43518
size_t myvar;
myvar = htonl(myvar); // For the endian issues
memcpy(buffer, &myvar, sizeof(size_t));
Upvotes: 2
Reputation: 70931
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
Upvotes: 2