Convert int to float in C (no casting) [closed]

2019-02-16 00:53发布

问题:

How do I convert an int to a float (returned as unsigned, but interpreted as a float)? I can't use any high level language constructs like unions, only bitwise ops, control logic (if/while), + and -, etc.

回答1:

Sure. You can certainly construct a floating point number from a raw byte buffer. Single precision floats are represented as 32-bit values in IEEE-754 and can represent the integer space quite easily. The wikipedia entry on IEEE floating point describes the various formats. All that you have to do is figure out which bits to set or test. Look at the wikipedia page on single-precision for a nice description of the bits. Here's a start:

float convert_int(unsigned int num) {
    float result;
    unsigned int sign_bit = (num & 0x80000000);
    unsigned int exponent = (num & 0x7F800000) >> 23;
    unsigned int mantissa = (num & /* insert mask value here */);

    /* you can take over from here */

    return result;
}

I left a lot up to the imagination, but I have a feeling that this is a homework problem. Once you understand the part that I have written, it should be easy enough to do the rest. A much nicer solution is to use a union, but I will leave that as an exercise to the reader as well.



回答2:

If you dont want to use any arithmetic or bitwise operators then you can use a method as

 float convrt(int x)
 {
  return x;
 }

It will return float... you can verify it in main as..

  void main()
 {
   int x=5;
   cout<<"size of x=" << sizeof(x);
   cout<<"size of convrt(x)=" << sizeof(convrt(x));
 }

it will give output as

    size of x=2
    size of convrt(x)=4

that means it gets converted into float. :-)