How does one safely static_cast between unsigned int and int?

后端 未结 6 1260
猫巷女王i
猫巷女王i 2021-02-19 19:36

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

6条回答
  •  猫巷女王i
    2021-02-19 20:15

    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.

提交回复
热议问题