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

标签 c floating-point numbers exponent

我正在编写一个函数来获取 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/

相关文章:

c - BZip2 解压非文件数据时不会出现错误?

python - 分数取模。分数类

math - float 学有问题吗?

shell - zsh while 循环在使用浮点运算的三重嵌套循环中过早退出

python - 将十进制数添加到十进制数在 python 中不能正常工作

C简单字符串程序无法编译

c - 如何动态分配(初始化)一个 pthread 数组?

c - 递归 C 字符串替换

javascript - 无穷大与 Number.POSITIVE_INFINITY

c# - 我必须使用什么正则表达式来分割它?