4 ms·
There is one strong difference between byteswap and other operations within <bit>. byteswap semantically works on the object representation of the integer, whi
by planede 4y ago
There is one strong difference between byteswap and other operations within <bit>.
byteswap semantically works on the object representation of the integer, while all other operations semantically work on the integer value, expressed in powers of two.
The C++ language has no strong requirements on the object representation of the underlying integer. The C++20 guarantee of two's complement also only just expressed in terms of integer value, not bit representation.
Therefor `byteswap` somewhat sticks out. It's possibly useful for `std::endian::little == std::endian::native` or `std::endian::big == std::endian::native`, and for `std::has_unique_object_representations_v<T> == true` (aka. no padding bits) for the corresponding integral type T. CHAR_BITS also change the semantics.
So, in this sense it is quite low level, and you have to check all of these to make use of it, or you have to implicitly rely on implementation defined values of these for the targets you care about.
I'm not saying that byteswap is not useful though. But it has the wrong interface. It reverses sequence of bytes, it does not work on integers.
edit:
Oh, in addition of having no padding bits, you also want no trap representations. I don't know if you can check for that.
edit2:
Apparently, you don't necessarily need to check for padding bits, byteswap does it for you, and fails to compile if there are padding bits:
https://eel.is/c++draft/bit#byteswap-2 https://eel.is/c++draft/bit#byteswap-2
I don't see trap representations being handled at all. This might be a defect.
- gpderetta 4y agoThanks, I didn't catch this difference between byteswap and the other <bits> functions.