What are the ntohl / NetworkToHostOrder equivalents?


I’m dealing with network packets and I can’t find an existing way to translate network byte order to Rust integer types. The std::io::Writer::write_be_u32 etc functions make for non-portable code since I have to check for the right one at every call. I’m hoping to avoid writing my own shift-mask-add macros or macros that detect endianness and expand to the correct call. Surely someone else must have done this already.

What I get is a packet where the internals contain “bytes 5…9: 32 bit int in network byte order” and in C I just go “ntohl(cast to int32)”. In practice I case the byte stream to a struct then process it, but that part is easy enough in Rust.

What’s the standard Rust way to do this endian-agnostic conversion?



If I’m interpreting your question right, then you specifically don’t want endian agnostic code. If you know you’re getting big endian values, then you should try to explicitly read big endian values into rust integer types. You can do that with the byteorder crate.


You’re right, I had it backwards. I just go “read big endian” and “write big endian” and it really is that simple.

Sorry, too much C has made me expect complexity :frowning:

Thanks for the quick reply.