如何将二进制数(32位)转换为十进制数?

时间:2015-04-01 08:44:54

标签: c binary ieee-754

我见过各种程序可以将给定的十进制浮点数转换为IEEE 754格式的二进制数。
现在,给定一个二进制数,如何在C中获取程序将其转换为浮点数?

示例:

Input:  01000001010010000000000001111111
Output: 12.50012111663818359375

1 个答案:

答案 0 :(得分:1)

我假设您将二进制表示形式设为string

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

void setBit(uint32_t* f, int i) {
    uint32_t mask = ((uint32_t)1) << i;
    *f |= mask;
}

float readFloat(const char* bits) {
    assert(strlen(bits)==8*sizeof(float));
    assert(sizeof(uint32_t)==sizeof(float));
    float f = 0;
    int size = strlen(bits);
    for (int i = 0; i < size; i++) {
        int bit = bits[size-i-1]- 0x30;
        if (bit) {
            setBit((uint32_t*)&f, i);
        }
    }
    return f;
}

int main(int argc, char *argv[]){
    const char* bits = "01000001010010000000000001111111";
    float f = readFloat(bits);
    printf("%s -> %.20f", bits, f);
}

给予

  

01000001010010000000000001111111 - &gt; 12.50012111663818359375