-1

I'm trying to understand, I'm a beginner.

I want to do arithmetic operations with float numbers in binary.

I was using http://www.binaryconvert.com/result_float.html to do the conversion

Only he returns me:

1069547520.000000
1069547520.000000
2139095040.000000

What is it?

I was hoping for this:

00111111110000000000000000000000
00111111110000000000000000000000
01000000010000000000000000000000

%f in printf() would be wrong too?

    #include <stdio.h>

    int main()
    {
        float a = 0b00111111110000000000000000000000; /* 1.5 */
        float b = 0b00111111110000000000000000000000; /* 1.5 */
        float c;

        c = a + b; /* 3.0 !? */

        printf("%f\n", a);
        printf("%f\n", b);
        printf("%f\n", c);

        return 0;
    }
  • 1
    "I want to do arithmetic operations with float numbers in binary." All arithmetic operations on all scalar types are done in binary. What do you \*really\* want? – Swordfish Oct 21 '18 at 14:22
  • I know the value that is returning me that I do not understand – Fabio Fontes Oct 21 '18 at 14:25

2 Answers2

4

The binary constant 0b00111111110000000000000000000000 is an extension of GCC, and it has type int having value 1069547520. This is converted to a float by the same value, i.e. the float closest to 1069547520.

There is no way of having floating point constants in binary in C; but hex is possible. If there were, then 1.5 would be expressed in binary simply as something like

0b1.1f 

i.e. its numeric value in binary is 1.1.

C17 (C99, C11) does have support for hexadecimal floating point constants; you can use

0x1.8p0f

for 1.5f; p0 signifies the exponent.

If you really want to fiddle with the IEEE 754 binary format, you need to use an union or memcpy. For example

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

int main(void) {
    float a;
    uint32_t a_v = 0b00111111110000000000000000000000;

    memcpy(&a, &a_v, sizeof(float));
    printf("%f\n", a);
    // prints 1.500000 on linux x86-64
}
1

Your binary literals are integer literals. Then you print the floating point values as floating point values, not using binary representation.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621