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?
Asked
Active
Viewed 248 times
0

MaMu
- 1,837
- 4
- 20
- 36
-
1Are 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
-
2On 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 Answers
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
-
For a pedantic solution, how about `32 == sizeof(s)*CHAR_BIT` or `sizeof(uint32_t) == sizeof(s)`? – chux - Reinstate Monica Oct 31 '14 at 19:01