如何获取浮点数的符号、尾数和指数 [英] How to get the sign, mantissa and exponent of a floating point number
问题描述
我有一个程序,它在两个处理器上运行,其中一个不支持浮点.因此,我需要在该处理器中使用定点执行浮点计算.为此,我将使用浮点仿真库.
我需要首先在支持浮点的处理器上提取浮点数的符号、尾数和指数.所以,我的问题是如何获得单精度浮点数的符号、尾数和指数.
按照该图的格式,
这就是我到目前为止所做的,但除了符号,尾数和指数都不正确.我想,我错过了一些东西.
void getSME(int&s,int&m,int&e,浮点数){unsigned int* ptr = (unsigned int*)&number;s = *ptr >>31;e = *ptr &0x7f800000;e>>= 23;m = *ptr &0x007fffff;}
我觉得用联合来做强制转换比较好,更清晰.
#include <stdio.h>typedef联合{浮动 f;结构{无符号整数尾数:23;无符号整数指数:8;无符号整数符号:1;} 部分;} float_cast;诠释主要(无效){float_cast d1 = { .f = 0.15625 };printf("sign = %x
", d1.parts.sign);printf("指数 = %x
", d1.parts.exponent);printf("mantisa = %x
", d1.parts.mantisa);}
示例基于 http://en.wikipedia.org/wiki/Single_precisionp>
I have a program, which is running on two processors, one of which does not have floating point support. So, I need to perform floating point calculations using fixed point in that processor. For that purpose, I will be using a floating point emulation library.
I need to first extract the signs, mantissas and exponents of floating point numbers on the processor which do support floating point. So, my question is how can I get the sign, mantissa and exponent of a single precision floating point number.
Following the format from this figure,
That is what I've done so far, but except sign, neither mantissa and exponent are correct. I think, I'm missing something.
void getSME( int& s, int& m, int& e, float number )
{
unsigned int* ptr = (unsigned int*)&number;
s = *ptr >> 31;
e = *ptr & 0x7f800000;
e >>= 23;
m = *ptr & 0x007fffff;
}
I think it is better to use unions to do the casts, it is clearer.
#include <stdio.h>
typedef union {
float f;
struct {
unsigned int mantisa : 23;
unsigned int exponent : 8;
unsigned int sign : 1;
} parts;
} float_cast;
int main(void) {
float_cast d1 = { .f = 0.15625 };
printf("sign = %x
", d1.parts.sign);
printf("exponent = %x
", d1.parts.exponent);
printf("mantisa = %x
", d1.parts.mantisa);
}
Example based on http://en.wikipedia.org/wiki/Single_precision
这篇关于如何获取浮点数的符号、尾数和指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!