So I’m constructing shorts/longs based on byte arrays here, and I wanted to avoid using memcpy to copy bytes into their own variable, and then assigning that variable to a sockaddr_in object.
Is there a better way to extract the short in the following statement?:
((sockaddr_in*)from)->sin_port = (*((unsigned short*)&buf[4]));
I did the whole pointer/dereference thing because, if my logic is correct, doing just an (unsigned short)buf[4] cast will only convert one byte; not both.
EDIT: Endianness is fine. I just want buf[4] and buf[5] to be together in one short in an easy way, other than having to use memcpy.
The code in your question:
may not work, due to the following issues:
memcpyis safe if you’re confident about the endianness (if not, then you should combine withntohsorntohl). A decent compiler should also optimize it away.If you really want to avoid
memcpy, then a safe, platform-independent way is something like the following (assuming thatbufwas originally populated from an external source, using standard network byte order):Of course, you should wrap that in a function (or a macro, if you must).