在 C++ 中添加 IEEE-754 浮点和浮点数

问题描述 投票:0回答:1

我有两个变量。

variable_1 = 01000001000011110101110000101001(IEEE-754 浮点格式为 0x410f5c29),十进制为 8.96。

float variable_2 = 0.2 

我想添加它们

float variable_3 = variable_1 + variable_2; // in C++

我只需要知道如何将它们分配给变量,以便它们保持原样。这将包括声明variable_1并为其分配值。

c++ ieee-754
1个回答
0
投票

将无符号整数设置为所需的位,然后使用

std::memcpy
将它们复制到
float
:

#include <cstdint>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <limits>


int main()
{
    uint32_t au = 0x410f5c29;
    float    a;

    static_assert(sizeof (float) == sizeof (uint32_t),
        "sizes of float and uint32_t must be the same");
    std::memcpy(&a, &au, sizeof a);

    float    b  = .2;
    float    c  = a+b;

    std::cout << std::setprecision(99);
    std::cout << "a = " << a << ".\n";
    std::cout << "b = " << b << ".\n";
    std::cout << "c = " << c << ".\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.