我有两个变量。
variable_1 = 01000001000011110101110000101001(IEEE-754 浮点格式为 0x410f5c29),十进制为 8.96。
float variable_2 = 0.2
我想添加它们
float variable_3 = variable_1 + variable_2; // in C++
我只需要知道如何将它们分配给变量,以便它们保持原样。这将包括声明variable_1并为其分配值。
将无符号整数设置为所需的位,然后使用
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";
}