Int for float with bitwise operators in C

I am writing a function to convert int to float with bitwise operators. I don't understand why my code doesn't work for all inputs. For example, it works for 2,19,43, etc., but it outputs -nan for 7,6,13,58 and so on. Can someone explain to me why this is happening? Thank you. Here is my code:

#include <stdio.h>

typedef union{
    int x;
    float fx;
}df;
int find_e(int x,int i){
    if(x&1<<i) return i;
    if(x==0) return -127;
    return find_e(x,--i);
}
float int_to_float(int x){
    df ime;
    ime.x=0;
    int sign = 0;
    if(x<0){x=-x;sign = 1<<31; }
    int position = find_e(x,31);
    int e = position + 127;
    int m = (x&(~(~0<<position)))<<(32-position);
    ime.x |= sign;
    ime.x |= e<<23;
    ime.x |= m>>9;
    return ime.fx;
}

int main()
{
    int x;
    scanf("%d",&x);
    printf("%f\n", int_to_float(x));
    return 0;
}

      

I am using the gcc compiler.

+3


source to share


1 answer


The problem is that type "m" is int

signed and the right shift will stretch.

ime.x |= m>>9;

      



Change any variables that cannot be negative before unsigned

instead int

.

I fixed it and made some minor changes: demo

+2


source







All Articles