简体   繁体   English

将浮点数转换为二进制

[英]Converting floating point to binary

#include <stdio.h>

void printBinary(int n, int i) {
    int k;
    for(k = i-1;k>=0;k--){
        if((n>>k)&1)
            printf("1");
        else
            printf("0");
    }
}
typedef union {
    float f;
    struct {
        unsigned int mantissa : 23; //4
        unsigned int exponent : 8; //3
        unsigned int sign : 1;
    }raw;
}myfloat;
void printIEEE(myfloat var){
    printf("%d | ", var.raw.sign);
    printBinary(var.raw.exponent,8); //3
    printf(" | ");
    printBinary(var.raw.mantissa, 23); //4
    printf("\n");
    
}
int main(){
    myfloat var;
    var.f = -4.25;
    printf("IEEE 754 represantation of %f is : \n",var.f);
    printIEEE(var);
    return 0;
}

I found this code from Inte.net.我从 Inte.net 找到了这段代码。 I get an error when I make some changes on it.当我对其进行一些更改时出现错误。 For example, i want to change the number.例如,我想更改号码。 I want to make 3 exponent and 4 mantissa when i change the number output is happening 0 000 0000.当我将数字 output 更改为 0 000 0000 时,我想生成 3 个指数和 4 个尾数。

Would you please try a cheat solution which share the bit pattern in the union:请您尝试一个在联合中共享位模式的作弊解决方案:

#include <stdio.h>
#include <stdint.h>

union ieee754 {
    uint32_t i;
    float f;
};

void printBinary(uint32_t n, int i) {
    uint32_t mask = 1 << (i - 1);
    do putchar(n & mask ? '1' : '0');
    while (mask >>= 1);
}

int main()
{
    union ieee754 var;
    var.f = -4.25;
    printf("IEEE 754 represantation of %f is:\n", var.f);
    printBinary(var.i, 32);
    printf("\n");

    return 0;
}

Output: Output:

IEEE 754 represantation of -4.250000 is:
11000000100010000000000000000000

Interpretation (or verification) of the bit pattern:位模式的解释(或验证):

11000000100010000000000000000000

sign bit ... 1
exponent ... 10000001 (= 129)
fraction ... 00010000000000000000000 (= 1/16)

decimal value = (-1)^1 * (1 + 1/16) * 2^(129 - 127))
              =  -4.250000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM