3 ms·
Yeah, for portable code you also need a function to tell you if you're on an architecture where you need to do a byteswap for the data you have. e.g. you know y
by Karellen 4y ago
Yeah, for portable code you also need a function to tell you if you're on an architecture where you need to do a byteswap for the data you have. e.g. you know you have data in little-endian format - do you need to swap it to work with it natively? That depends.
Maybe having something like convert_be() and convert_le(), one of which is a no-op and the other does the byteswap (depending on your arch) would be better. It removes the duplication of e.g. htobe() and betoh() which are exactly the same function, while allowing the caller to not worry about which architecture their code is compiled on.
- apaprocki 4y agoI view it more as a platform-independent building block to be used by library authors. For instance, here's our suite of byte order macros that this will not simply replace: https://bloomberg.github.io/bde-resources/doxygen/bde_api_prod/group__bsls__byteorder.html https://bloomberg.github.io/bde-resources/doxygen/bde_api_pr...
- gpderetta 4y agoYes, there is also std::endian::{big, small, native} that can be used to check if you need to byteswap or not. So a generic hton* is just: auto to_network_endian(auto std::integral value) { if constexpr (std::endian::native != std::endian::big) { return std::byteswap(value); } else { return value; } } ntoh is left as an exercise :). edit: in practice I think std::endian and std::byteswap is a compromise between those that wanted a simple {to,from}_network_endian and those that wanted strongly typed wrappers to prevent mixing object with distinct endianess (a-la boost::endian). As the commitee couldn't reach consensus, this is the compromise and you can build your own thing with these portable bits.
- yrro 4y agoHuh. You know I had never considered why we have htobe32 and be32toh which do exactly the same thing. Maybe because of oddball architectures which are neither big nor little endian? For instance... /usr/include/x86_64-linux-gnu/bits/endian.h has: #define __LITTLE_ENDIAN 1234 #define __BIG_ENDIAN 4321 #define __PDP_ENDIAN 3412 Apparently this is called 'middle-endian'... yikes! On the other hand I sort of like having one function that's clearly used for importing values to the host's byte order, and another for exporting values from the host's byte order. But maybe that's just because I'm used to having them...
- beached_whale 4y agoThose are in <bit> as of c++20