Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Re 3), all the <bits> instructions can be expressed in high level code, and compilers have been able to convert high level code to the actual machine instructions for a while.

The issue is exactly which code pattern is detected by which compiler varies a lot, so to avoid having to rely on that there was a strong push to add all these explicit intrinsics. Also std::bytesewap is more readable than the longer reverse+as_writeable_bytes.



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

I don't see trap representations being handled at all. This might be a defect.


Thanks, I didn't catch this difference between byteswap and the other <bits> functions.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: