-1

An unsigned long long variable has the value of "40 36 70 A3 D7 0A 3D 71" in hex. If I print it with the %fconversion specifier I get the right conversion from IEEE-754. How can I cast this variable to a floating one or int, even if I lose some decimals?

I have tried casting it but it gives me bad values. Example here:

unsigned long long hex = 0x403670A3D70A3D71;
float cast_float = (float)hex;
  • You cannot successfully convert it to `int` because it is out of range of `int`, but you can convert it to an approximate `float` value with `(float)myull`. But I don't understand what you mean by "If I print it as %f I get the right conversion from IEEE-754" so please **show the actual code** you are using. – Weather Vane Mar 02 '20 at 14:20
  • Did you mean `double`? That is the same size as `unsigned long long` but `float` is not. – Weather Vane Mar 02 '20 at 14:23
  • 1
    What exactly do you mean by "If I print it as %f"? The likely -- but undefined(!) -- behavior of passing your variable `hex` to `printf` as the argument corresponding to a `%f` directive is completely different from the behavior to be expected from converting that variable's value to `float` or `double` via a cast. Do you mean to work on the variable's *value* or on its *representation*? – John Bollinger Mar 02 '20 at 14:35
  • Don't you need `UL` on the end of the literal? – stark Mar 02 '20 at 14:38
  • "I have tried casting it but it gives me bad values." --> what was the bad value? What was expected? – chux - Reinstate Monica Mar 02 '20 at 14:52
  • @stark `UL` suffix would not make a difference here. – chux - Reinstate Monica Mar 02 '20 at 14:52

1 Answers1

1

Assuming that the unsigned long long variable contains a value that is a valid double value, then you could use type punning, for example using unions:

union
{
    unsigned long long i;
    double             f;
} value = { .i = 0x403670A3D70A3D71 };

printf("0x%llx is %f\n", value.i, value.f);

Note that this is valid only if the value in the integer have the same bit-pattern as a valid double-precision floating point value on your system. Otherwise it could lead to undefined behavior.


Now if you want to convert it to the int value 22 (as 0x403670A3D70A3D71 is the binary representation of the double value 22.44), then you first need to use type-punning to get the floating point value, then use the floor function to truncate it to an integer value (but still in floating point type), and lastly cast that to an int:

int int_val = (int) floor(value.f);
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550