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

前端 未结 6 1944
悲哀的现实
悲哀的现实 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: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++.

提交回复
热议问题