gpt4 book ai didi

c - 从 C 中的 float 获​​取指数

转载 作者:太空宇宙 更新时间:2023-11-04 05:25:08 25 4
gpt4 key购买 nike

我正在编写一个函数来获取 float (IEEE 754 标准)的指数,但出于某种原因,当我对数字使用右移按位运算符时,它返回 0

这是函数

int get_exp (int x) 
{
return ( ((x >> 21) & 255) -127 );
}

我将它传递给 7.23,所以输出应该是 2,出于某种原因,(x >> 21) 部分实际上应该返回 129 时返回 0。255 是我使用的掩码和 (& ) 与 float 的指数部分。

最佳答案

我猜你正在做某种类型的转换把 float 作为 int 传递秒?我会用 float frexpf (float x, int* exp);<math.h> 中所定义.

#include <math.h>

int get_exp(float x)
{
int exp;
frexpf(x, &exp);
return exp;
}

无论浮点类型的大小如何,它都能保证工作。

如果你想自己滚动,你可以修改这个代码。

#define EXPONENT_BIAS (-127)

int get_exp(float f)
{
int i;
union {
// Set here, then use s or c to extract
float f;
// This may or may not work for you
struct {
unsigned int sign: 1;
unsigned int exponent: 8;
unsigned int mantissa: 23;
} s;
// For debugging purposes
unsigned char c[sizeof(float)];
} u;

// Assign, you might need to reverse the bytes!
u.f = f;

// You'll probably need this to figure out the field widths
for (i = 0; i < sizeof(float); i++)
fprintf(stderr, "%02x%s", u.c[i], (i + 1 < sizeof(float))? " ": "\n");

// Just return the exponent
return (int)u.s.exponent + EXPONENT_BIAS;
}

如果 sizeof(float) != 4 这会咬你,或者如果您切换字节顺序。

关于c - 从 C 中的 float 获​​取指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32659336/

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