Kar*_*sef 0 c floating-point numbers exponent
我正在编写一个函数,它将获得浮点数(IEEE 754标准)的指数但由于某种原因,当我在数字上使用右移位运算符时,它返回0
这是功能
int get_exp (int x)
{
return ( ((x >> 21) & 255) -127 );
}
Run Code Online (Sandbox Code Playgroud)
我传递它7.23所以输出应该是2,由于某种原因,(x >> 21)部分返回0时它应该实际返回129. 255是我正在使用的掩码和(&)与指数浮点数的一部分.
我猜你正在做某种投射hocus-pocus来传递浮点作为ints?我会float frexpf (float x, int* exp);按照定义使用<math.h>.
#include <math.h>
int get_exp(float x)
{
int exp;
frexpf(x, &exp);
return exp;
}
Run Code Online (Sandbox Code Playgroud)
无论浮点类型的大小如何,它都可以保证工作.
如果您想自己滚动,可以调整此代码.
#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;
}
Run Code Online (Sandbox Code Playgroud)
sizeof(float) != 4如果你转换了endian-ness,这会咬你.