Casting float to int (bitwise) in C

前端 未结 7 1034
甜味超标
甜味超标 2020-11-27 21:27

Given the 32 bits that represent an IEEE 754 floating-point number, how can the number be converted to an integer, using integer or bit operations on the representation (rat

7条回答
  •  臣服心动
    2020-11-27 21:40

    You can cast the float using a reference. A cast like this should never generate any code.

    C++

    float f = 1.0f;
    int i = (int &)f;
    printf("Float %f is 0x%08x\n", f, i);
    

    Output:

    Float 1.000000 is 0x3f800000
    

    If you want c++ style cast use a reinterpret_cast, like this.

    int i = reinterpret_cast(f);
    

    It does not work with expressions, you have to store it in a variable.

        int i_times_two;
        float f_times_two = f * 2.0f;
        i_times_two = (int &)f_times_two;
    
        i_times_two = (int &)(f * 2.0f);
    main.cpp:25:13: error: C-style cast from rvalue to reference type 'int &'
    

提交回复
热议问题