gpt4 book ai didi

c++ - 将符号位、指数和尾数转换为 float ?

转载 作者:搜寻专家 更新时间:2023-10-31 00:28:22 24 4
gpt4 key购买 nike

我有符号位、指数和尾数(如下面的代码所示)。我正在尝试获取此值并将其转换为 float 。这样做的目标是获得 59.98 (它会读作 59.9799995 )

uint32_t FullBinaryValue = (Converted[0] << 24) | (Converted[1] << 16) |
(Converted[2] << 8) | (Converted[3]);

unsigned int sign_bit = (FullBinaryValue & 0x80000000);
unsigned int exponent = (FullBinaryValue & 0x7F800000) >> 23;
unsigned int mantissa = (FullBinaryValue & 0x7FFFFF);

我最初尝试做的只是一点一点地把它们放在它们应该在的地方:

float number = (sign_bit << 32) | (exponent << 24) | (mantissa);

但这给了我 2.22192742e+009.

然后我打算使用公式:1.mantissa + 2^(exponent-127)但是你不能在二进制数中放置小数位。

然后我尝试获取(指数、特征、后尾数)的每个值,然后我得到了

Characteristic: 0x3B (Decimal: 59)
Mantissa: 0x6FEB85 (Decimal: 7334789)
Exponent: 0x5 (Decimal: 5) This is after subtracting it from 127

然后我打算把这些数字改造成 printf。但我不知道如何将尾数十六进制转换为它应该的样子(幂为负指数)。

关于如何将这三个变量(符号位、指数和尾数)转换为 float 有什么想法吗?

为 PAUL R 编辑这是最小、完整和可验证格式的代码。我添加了 uint8_t Converted[4]那里只是因为它是我最终得到的值(value),它使它可以运行。

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
uint8_t Converted[4];
Converted[0] = 0x42;
Converted[1] = 0x6f;
Converted[2] = 0xEB;
Converted[3] = 0x85;

uint32_t FullBinaryValue = (Converted[0] << 24) | (Converted[1] << 16) |
(Converted[2] << 8) | (Converted[3]);

unsigned int sign_bit = (FullBinaryValue & 0x80000000);
unsigned int exponent = (FullBinaryValue & 0x7F800000) >> 23;
unsigned int mantissa = (FullBinaryValue & 0x7FFFFF);

float number = (sign_bit) | (exponent << 23) | (mantissa);

return 0;
}

最佳答案

问题是表达式 float number = (sign_bit << 32) | (exponent << 24) | (mantissa);首先计算一个 unsigned int然后将该值转换为 float .基本类型之间的转换将保留值而不是内存表示。您要做的是将内存表示重新解释为不同的类型。您可以使用 reinterpret_cast .

试试这个:

uint32_t FullBinaryValue = (Converted[0] << 24) | (Converted[1] << 16) |
(Converted[2] << 8) | (Converted[3]);


float number = reinterpret_cast<float&>(FullBinaryValue);

关于c++ - 将符号位、指数和尾数转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45512768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com