I have an 8-character string
representing a hexadecimal number and I need to convert it to an int
. This conversion has to preserve the bit pattern for
C++20 will have std::bit_cast that copies bits verbatim:
#include
#include
#include
int main()
{
int i = -42;
auto u = std::bit_cast(i);
// Prints 4294967254 on two's compliment platforms where int is 32 bits
std::cout << u << "\n";
auto roundtripped = std::bit_cast(u);
assert(roundtripped == i);
std::cout << roundtripped << "\n"; // Prints -42
return 0;
}
cppreference shows an example of how one can implement their own bit_cast
in terms of memcpy
(under Notes).
While OpenVMS is not likely to gain C++20 support anytime soon, I hope this answer helps someone arriving at the same question via internet search.