gpt4 book ai didi

c - 二进制到 float

转载 作者:行者123 更新时间:2023-12-01 12:42:17 25 4
gpt4 key购买 nike

我想从它们的二进制表示中生成浮点变量,我很快想出了以下代码:

float bintofloat(unsigned int x) {
float *f = (float *)&x;
return *f;
}

然后可以按如下方式调用上述函数:
float f = bintofloat(0x3f800000);

我只是希望得到一些关于这种方法的意见:使用指针是否是最好的方法,或者是否有更好或更简洁的方法?

不幸的是,我对类型的使用似乎分散了注意力。我为此道歉;为了简单起见,我选择坚持使用内置类型。但我确实承认它很幼稚,并假设 sizeof(int) == sizeof(float) .

同样,我的主要问题是使用指针是否是实现从二进制到浮点的这种转换的好方法?

最佳答案

在您的代码中,在函数 bintofloat() 中以下地址转换和取消引用无效:

float *f = (float *)&x;
return *f;

这将在运行时调用未定义的行为。

EXP36-C. Do not cast pointers into more strictly aligned pointer types

Do not convert a pointer value to a pointer type that is more strictly aligned than the referenced type. Different alignments are possible for different types of objects. If the type-checking system is overridden by an explicit cast or the pointer is converted to a void pointer (void *) and then to a different type, the alignment of an object may be changed.

The C Standard, 6.3.2.3, paragraph 7 [ISO/IEC 9899:2011], states:

A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.



如果未对齐的指针被取消引用,程序可能会异常终止。在某些体系结构上,如果所涉及的类型具有不同的对齐要求,即使该值没有被取消引用,单独的转换也可能导致信息丢失。

在您的代码中 x是 unsigned int ,它具有与浮点类型不同的内存对齐方式。

类型转换 float *f = (float *)&x;是有效的,但一般来说不是好主意。浮点型指针应指向浮点型。某些系统甚至可能在将无符号 int* 延迟为 float* 时给程序一个致命的 SIGBUS,因为 float 需要更严格的地址对齐到 sizeof(float) 的倍数。

当您编写通用代码时,批准的分配未知类型地址的方法是使用 void* ,但要取消引用,您必须将其转换为正确的类型,因此实际上以下代码是错误的:
unsigned int x = 10U;
unsigned int *xp = &x;
void* vp = x;
float* fp = vp;
float f = *fp;

link从我引用的地方给你一些更多的例子来帮助你理解这个问题。

您还应该阅读此 Keith Thompson的回答: What is the difference between float pointer and int pointer address?

编辑:我认为您可以执行以下操作:
#include<stdio.h>
float bintofloat(unsigned int x) {
union {
unsigned int x;
float f;
} temp;
temp.x = x;
return temp.f;
}

int main(){
float f = bintofloat(0x4236AE14U);
printf ("\nf = %f ", f);
printf ("\nf = %f \n", bintofloat(0x4287F0A4U));
return 0;
}

将其用作:
$ gcc -Wall -pedantic binarytofloat.c
taxspanner@:~$ ./a.out

f = 45.669998
f = 67.970001

检查以下浮点精度 IEEE754 计算器的链接:
  • 0x4236AE14U
  • 0x4287F0A4U
  • 关于c - 二进制到 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23265265/

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