Home > OS >  C 20 feature std::bit_cast : what happens to the value while reinterpreting type from to type to
C 20 feature std::bit_cast : what happens to the value while reinterpreting type from to type to

Time:01-29

std::cast in C 20 is a safer version of reinterpret_cast that works with constexpr so I read, but does that mean the actual value of the variable involved also gets reinterpreted bitwise? e.g. following simple code

#include #include

#include <iostream>
#include <bit>

int main()
{
    float f = 123.017;
    auto f_int = std::bit_cast<int>(f);

    std::cout << "f : " << f << ", f_int : " << f_int << std::endl;
}

produces this output

f : 123.017, f_int : 1123420340

I am trying to use std::bit_cast to safely reinterpret data type hoping to retain narrowing version of the original data value, which obviously didn't happen.

CodePudding user response:

std::bit_cast is the same as memcpy, the bits of the original are the same as the converted value. You might be after static_cast:

#include <bit>
#include <stdio.h>

using namespace std;

int main()
{
    float f = 123.017;
    auto a = static_cast<int>(f);
    auto b = std::bit_cast<int>(f);
    
    printf("f: %f a: %d b: %d\n", f, a, b); // f: 123.016998 a: 123 b: 1123420340

    return 0;
}
  • Related