简体   繁体   中英

Is using the Boost Endian Arithmetic types considered good practice?

I'm fairly new at a company as embedded software engineer and I have to deal with networking quite a lot. I have to program in C++ all the time and using the code of my colleagues I noticed they use structs to build up packets to send over a network using TCP/UDP. For this, because the machines we are using are little-endian, everything has to be converted to big-endian. So the moment the data has to be sent they use the known functions as htons, ntohs, etc.

So I was looking up on how to make my code portable so the programmer does not have to care about the endianness of his machine and I stumbled upon the Endian Arithmetic types of the Boost library with which you, the programmer, can decide how your integer types are stored in memory. They seem very nice in the context I would use them but they are mentioned barely anywhere. Stackoverflow only has posts on how the endianness problem can not be handled in a proper way but these Arithmetic types seem like a nice portable solution to me. Why is it these types are barely mentioned anywhere and are never a proposed solution? Is there something wrong with them or are they just too new?

It depends on where. Of course, using them throughout your whole codebase is a design trade-off.

The endian types are not a zero-cost abstraction. Using them for anything else than passive storage can hurt performance. (Imagine doing number crunching on non-native endian numbers. The processor could be spending more time dancing around with high-order/low-order bytes and words as needed than on the actual calculations).

If your application is typical, you will have POD transmission buffers that do not contain many "live" data elements, and the sheer benefit of automatic endianness conversions under the hood could well be worth any overhead.

I know about Boost Endian types and would prefer them over repeatedly writing ntoh and friends in a heartbeat.

In reality, though I've written generic serialization helpers (where the use of ntoh / hton is isolated to a handful primitive functions), or used existing libraries (such as protobuf). So the irony is that, me too, I haven't use Boost Endian extensively for any production code.

Perhaps this pattern goes for many developers, explaining not a lot of examples around Boost Endian?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM