c - How can I convert a binary number (32 bit) to a decimal number? -
i've seen various programs can convert given decimal floating point number, binary in ieee 754 format.
now, given binary number, how can program in c convert floating point number?
example:
input: 01000001010010000000000001111111 output: 12.50012111663818359375
i'm assuming have binary representation 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); (int = 0; < 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
Comments
Post a Comment