如何在C/C ++中将1编码为浮点数(假设采用IEEE 754单精度表示)? [英] How is 1 encoded in C/C++ as a float (assuming IEEE 754 single precision representation)?

查看:180
本文介绍了如何在C/C ++中将1编码为浮点数(假设采用IEEE 754单精度表示)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是C float有8位指数和23位尾数.

My impression is that C float has 8 bits of exponent and 23 bits of mantissa.

所以一个是0011 1111 1000 0000 0000 0000 0000 0000 = 0x3F800000.

So one is 0011 1111 1000 0000 0000 0000 0000 0000 = 0x3F800000.

但是,以下代码产生的是1.06535e + 09,而不是1. 谁能帮我理解为什么?

However, the following code produced 1.06535e+09 instead of 1. Can anyone help me understand why?

#include <iostream>
#include <math.h>  

using namespace std;

int main()
{
    float i = 0x3F800000;
    cout<<i << endl;
    return 0;
}

推荐答案

在C中如何将1编码为浮点数?

How is 1 coded in C as a float?

任何人都可以帮助我理解为什么(代码失败)吗?

Can anyone help me understand why (code fails)?

float i = 0x3F800000;

i = 1065353216相同;

在C语言中,使用unionmemcpy()覆盖位模式.

In C, to overlay the bit pattern use a union or use memcpy().

在C ++中,建议使用memcpy().

In C++, suggest memcpy().

使用演员表会因抗锯齿而导致失败. @Eric Postpischil

Using a cast risks failure due to anti-aliasing. @Eric Postpischil

#include <stdio.h>
#include <stdint.h>

_Static_assert(sizeof(float) == sizeof(uint32_t), "Unexpected types");

int main(void) {
  union {
    uint32_t u; 
    float f;
  } x = {.u = 0x3f800000};
  float f = x.f;
  printf("%e\n", f);
  return 0;
}

在不太常见的系统上,这可能由于以下原因而失败

On less common systems, this can fail due to

Endian在float/uint32

这篇关于如何在C/C ++中将1编码为浮点数(假设采用IEEE 754单精度表示)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆