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

epggiuax  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(153)

我有两个变量。

variable_1=01000001000011110110000101001(IEEE-754浮点格式中为0x 410 f5 c29),在十进制中为8.96。

float variable_2 = 0.2

我想把它们加进去

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

我只需要知道如何将它们分配给变量,以便它们被取为它们是什么。这将包括声明variable_1并为其赋值。

z31licg0

z31licg01#

将一个无符号整数设置为所需的位,并使用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";
}

样品输出:

a = 8.96000003814697265625.
b = 0.20000000298023223876953125.
c = 9.159999847412109375.

相关问题