【问题标题】:Cast value without changing underlying bits在不改变底层位的情况下转换值
【发布时间】:2022-10-01 07:59:08
【问题描述】:

我前段时间在谷歌上搜索了这个,什么也没想到,不得不求助于铸造指针,这有点笨拙:

constexpr float value = 205.5f;
const auto float_as_unsigned =*((uint32_t*)&value);

我刚刚意识到你可以用工会做到这一点:

union bit_cast32
{
    float f32;
    uint32_t u32;
    int32_t i32;
};
const auto value_as_unsigned2 = bit_cast32( 205.5f ).u32;

有没有更好的办法?

    标签: c++ c++20


    【解决方案1】:

    是的,对于 c++20 来说是新的,有 std::bit_cast

    constexpr auto value_as_unsigned3 = std::bit_cast<uint32_t, float>(205.5f);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      相关资源
      最近更新 更多