1
\$\begingroup\$

I wrote a program to convert float to it's binary IEEE754 representation in C.

Any improvements to this is appreciated

#include <stdio.h>
#include <stdlib.h>
void binary(float num) {
    int n = *(int *) &num; //Evil bit hack from Quake3 Q_sqrt function
    int size = sizeof(n) * 8; 
    char *s = malloc(1 + size); //A string which can hold 32 characters
    s[size] = '\0';
    int index = size - 1;
    while(index >= 0) {
        if (n & 1)
            *(s + index) = '1';
        else
            *(s + index) = '0';
        n >>= 1;
        index--;
    }
    printf("%s\n", s);
    free(s);
}

int main(void) {
    float num;
    scanf("%f", &num);
    binary(num);
}
\$\endgroup\$
5
  • \$\begingroup\$ try the itoa() function \$\endgroup\$
    – Hannah W.
    May 2 at 15:17
  • \$\begingroup\$ C--, is the goal to dump the binary data stored in a float or "convert float to it's binary IEEE754" (even when float is not encoded as IEEE754)? \$\endgroup\$ May 5 at 18:31
  • \$\begingroup\$ @chux-ReinstateMonica I had initial impression all C compilers would store floats in IEEE 754 representation. So, I have assumed this to be true. But looking at my code, it just dumps binary data stored in float \$\endgroup\$
    – C--
    May 7 at 6:11
  • \$\begingroup\$ @HannahW. Thanks for your response. Although I'm looking it to solve without using ready-made functions. \$\endgroup\$
    – C--
    May 7 at 6:14
  • \$\begingroup\$ Please don't update the code in your question after receiving answers. Doing so would make it very confusing for future readers and reviewers. If you have new code you want reviewed, please post a new question with a link to the old one. If you don't want to have your new code and just want to share it with us, you can post it as an answer. Please note that all answers must be reviews and thus mention what you changed and why, like a review, to be an acceptable answer. Thank you. \$\endgroup\$
    – Mast
    May 7 at 7:02
2
\$\begingroup\$

IEEE754 conformance

Compilers aren't required to support IEEE754 decimals. Most implementations do, but regardless, it's better to check for maximum portability. If you're using C99 or later, the macro __STDC_IEC_559__ is defined whenever IEEE754 is supported.


sizeof(int)

Similarly, int isn't guaranteed to be 32 bits. The compiler only guarantees a minimum size of 16 bits. You can use the fixed width integer types defined in stdint.h i.e. uint32_t or int32_t.


Use size_t instead of int

The proper type for sizeof expression is size_t. As a general use, any variable representing size or index should be size_t.


Since you're not using s outside of the binary function, you can just allocate a fixed an array of size 33 on the stack instead of on the heap using malloc.

static const size_t num_bits = 33;
char s[num_bits];

*(s + index) is just fancy way to write s[index]. The latter is much cleaner, IMO and much more easier to understand for someone who isn't familiar with pointer arithmetic.

\$\endgroup\$
5
  • \$\begingroup\$ The benefit of the stack usage change cannot be underestimated .. Memory allocation is much much slower (even just the overhead of a function call) than just referencing the space the compiler has allowed for / left (compile time cost for runtime benefit !!). \$\endgroup\$
    – Mr R
    May 1 at 0:27
  • 2
    \$\begingroup\$ Your wording about IEEE754 conformance is slightly incorrect. It's the C standard that does not require an implementation to support IEEE754. However, the compilers themselves are not free to choose what they implement, they are bound by what the platform ABI specifies the format of float and double should be. The same goes for the size of integer types. \$\endgroup\$
    – G. Sliepen
    May 1 at 7:25
  • \$\begingroup\$ Hmm, I was not aware of that but it makes sense. Thanks! \$\endgroup\$
    – Rish
    May 1 at 8:34
  • \$\begingroup\$ @Rish Thanks for the answer, Although I don't understand why all compilers not use IEEE 754 representation to store float. If not, what's the most common way to store floats or double(To be precise single/double precision literals)? By the way, I'm compiling the above program on gcc shipped with ubuntu LTS \$\endgroup\$
    – C--
    May 1 at 13:51
  • 1
    \$\begingroup\$ @G.Sliepen C is popularly used in embedded situations where the is no ABI specifics and compiler can use any FP encoding. Even in ABI specifics, that often refers to the encoding only. Complete adherence to quality handling of sub-normals, -0.0, inf, NaN is wide ranging. Certainly interface requirements strongly influence the code a compiler makes, yet there remains much wiggle room. In the case were the processor directly implements FP, that tends to dominate. Yet without FP hardware (100s of millions/yr of those little embedded processors), be prepared for variety. \$\endgroup\$ May 7 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.