Pedro Cabaço
Pedro Cabaço

Reputation: 123

How can I convert a binary number (32 bit) to a decimal number?

I've seen various programs where I can convert a given decimal floating point number, to a binary in the IEEE 754 format.
Now, given a binary number, how can I get the program in C to convert it to a floating point number?

Example:

Input:  01000001010010000000000001111111
Output: 12.50012111663818359375

Upvotes: 0

Views: 977

Answers (1)

T.Gounelle
T.Gounelle

Reputation: 6033

I'm assuming you have the binary representation as a 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);
}

Gives

01000001010010000000000001111111 -> 12.50012111663818359375

Upvotes: 1

Related Questions