get the integer representation value of a float type variable in C

前端 未结 6 1929
悲哀的现实
悲哀的现实 2020-12-21 13:19

I have the number 20 (0x14) stored in a 32-bit register. The register is allocated to a C float variable representing the value 2.8e-44. Now I want to get the hexadecimal re

相关标签:
6条回答
  • 2020-12-21 13:27

    you can use type casting ..

    float x =3.4;
    int y = (int)x;
    
    0 讨论(0)
  • 2020-12-21 13:32

    Note that the behaviour of (int*)&f is undefined as the pointer types are unrelated. So don't approach the problem in that way.

    Having checked that sizeof(float) is the same as sizeof(int), you could do this in one of two ways:

    1) Type pruning through a union consisting of a float, and an int. Set the union using one member, and read it back with the other.

    2) memcpy the contents of a variable of one type to the location of the variable of the other type.

    Of these I prefer (2): (1) might be undefined with older C standards, and (2) also works well with C++.

    0 讨论(0)
  • 2020-12-21 13:46

    You can directly cast it to integer as;

    float a = 7.4;
    int b = a; // this will be rounded to 7 and you will lose information
    

    Or you can use some built-int functions like round, ceil, floor etc.

    For reference: http://www.cplusplus.com/reference/cmath/round/?kw=round

    0 讨论(0)
  • 2020-12-21 13:47

    You can achieve your need with a union:

    #include <stdio.h>
    
    int main()
    {
      union { int i; float f; } fi;
      fi.f = 2.802597e-44;
      printf("f=%e\n",fi.f);
      printf("n=%d\n",fi.i);
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-21 13:49

    C is considered a weakley typed langauge, which may allow to assign values that belong to different types than the variable they are being assigned with, therefore you can simply do this:

     int integer = 1;  
     float floater =1.1111;
    
     floater = integer;  
    

    This is known as Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. Some programming languages allow compilers to provide coercion; others require it.

    but consider the following:

    • what happens when the float is less than zero?
    0 讨论(0)
  • 2020-12-21 13:53

    What are you doing there is Undefined Behavior, didn't you check the warning?

    warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
         printf("n=%d\n",f);
         ^
    

    Read this please: How do the digits 1101004800 correspond with the number 20?

    0 讨论(0)
提交回复
热议问题