1

我写了这个程序:

#include <stdio.h>
#include <stdint.h>
/*
 * See also : http://class.ece.iastate.edu/arun/CprE281_F05/ieee754/ie5.html
 */

union FloatingPointSinglePrecisionIEEE754 {
    struct {
        unsigned int mantissa : 23;
        unsigned int exponent : 8;
        unsigned int sign : 1;
    } raw;
    float f;
} fnumber;

union FloatingPointDoublePrecisionIEEE754 {
    struct {
        uint64_t mantissa : 52;
        unsigned int exponent : 11;
        unsigned int sign : 1;
    } raw;
    double d;
} dnumber;



int main() {

    printf("sign\texponent\tmantissa\n");

    fnumber.f = -6.8;
    printf("%x\t%x\t\t%x\n",
            fnumber.raw.sign,
            fnumber.raw.exponent,
            fnumber.raw.mantissa); 


    dnumber.d = -6.8;
    printf("%x\t%x\t\t%x\n",
            dnumber.raw.sign,
            dnumber.raw.exponent,
            dnumber.raw.mantissa); 


return 0;
}

对于单精度,我得到了真正的输出,但对于双精度,程序失败了。任何人都可以帮助我如何编写双精度转换器?

4

3 回答 3

2

下面的程序似乎对我有用。我得到:

sign    exponent    mantissa
1   81      59999a
1   401     b333333333333

我所做的两个更改是在中使用正确的 C99 格式(有关这些格式的信息,请参见此维基百科页面)PRIx64并对. 众所周知,位域的指定不足,但使用不同的基本类型可能会导致编译器开始一个新单词,而不是你想要的。printf()union FloatingPointDoublePrecisionIEEE754

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
/*
 * See also : http://class.ece.iastate.edu/arun/CprE281_F05/ieee754/ie5.html
 */

union FloatingPointSinglePrecisionIEEE754 {
    struct {
        unsigned int mantissa : 23;
        unsigned int exponent : 8;
        unsigned int sign : 1;
    } raw;
    float f;
} fnumber;

union FloatingPointDoublePrecisionIEEE754 {
    struct {
        uint64_t mantissa : 52;
        uint64_t exponent : 11;
        uint64_t sign : 1;
    } raw;
    double d;
} dnumber;



int main() {

    printf("sign\texponent\tmantissa\n");

    fnumber.f = -6.8;
    printf("%x\t%x\t\t%x\n",
            fnumber.raw.sign,
            fnumber.raw.exponent,
            fnumber.raw.mantissa); 


    dnumber.d = -6.8;
    printf("%x\t%x\t\t%" PRIx64 "\n",
            dnumber.raw.sign,
            dnumber.raw.exponent,
       (uint64_t)dnumber.raw.mantissa); 


return 0;
}
于 2013-05-29T09:40:22.287 回答
1

当您尝试使用简单的格式化程序printf输出 64 位无符号整数时,可能是您失败了。%x将 a%xl用于“长”无符号整数:

dnumber.d = -6.8;
printf("%x\t%x\t\t%xl\n",  // note the %xl format specifier for the mantissa
        dnumber.raw.sign,
        dnumber.raw.exponent,
        dnumber.raw.mantissa); 

请参阅printf 参考

于 2013-05-29T08:30:20.767 回答
1

python代码很简单如下:

def hb(a):
    ab = bin(int(a[:3],16))[2:]
    if len(ab)==12:
        sgn=1
        ex=int(ab[1:], 2)-1023
    else:
        sgn=0
        ex=int(ab, 2)-1023
    return(((-1)**sgn)*(1.0 + ((int(a[3:],16))/(2.0**52)))*(2**ex))
于 2015-02-09T10:24:51.617 回答