2

I'm new to C and I tried following:

float f = 0x41933333;

this should give me the float number: 18.4 but when I look into the memory I find the hex value:

66 26 83 4e

which is as float: 41933333.0000

Why is my hex value interpreted as a decimal number?

Pavel
  • 7,168
  • 2
  • 28
  • 41
Zteve
  • 341
  • 1
  • 2
  • 12
  • 1
    Are you really sure with the number you are quoting as your results? As `float f = 0x41933333;` shall give `1.10016589e+09`for `f`. – alk Jun 05 '14 at 17:47

3 Answers3

3

0x41933333 is an integer constant. When assigned to a float, the integer is converted. If you need a hexadecimal floating point constant, you have to use that notation explicitly:

0x0.933333P4

or something vaguely similar — I've only made a casual guess at what the correct value is, but the 0x prefix and the P exponent are crucial parts of a hexadecimal floating point constant. See section 6.4.4.2 Floating constants in ISO/IEC 9899:2011 for the full details.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
0

If you want to plug in the raw value directly, use a union.

Jiminion
  • 5,184
  • 1
  • 25
  • 52
-1

alternatively, you can perform a casting by interpreting the value of an int as float

unsigned int n = 0x41933333;
float f = *((float*)&n);
Pavel
  • 7,168
  • 2
  • 28
  • 41
  • Thanks, that worked for me :) – Zteve Jun 05 '14 at 18:02
  • 3
    This only works if the size of an `int` is the same as the size of a `float`. – alk Jun 05 '14 at 18:04
  • This methods violates C’s aliasing rules (C 2018 6.5 7) and is unnecessary because an interpretation of desired bits as a floating-point object can be performed properly using `memcpy` (in C or C++) or a union (in C). – Eric Postpischil Aug 08 '19 at 19:37