11 years, 6 months ago.

I want to get the only sign of a value.

If i get float a=-1.5, how could I get the only sign of a?

I just want to get sign of a : (-1)

2 Answers

11 years, 6 months ago.

From https://en.wikipedia.org/wiki/IEEE_754-1985, the sign bit is at 31st bit.

#include <stdio.h>

int main()
{
    float f1 = -1.2;
    float f2 =  1.2;
    int sign1 = (int) f1 >> 31;
    int sign2 = (int) f2 >> 31;
    printf("sign of %f = %d\n", sign1, f1);
    printf("sign of %f = %d\n", sign2, f2); 
   
   return 0;
}

Output:

sign of -1.200000 = -1
sign of 1.200000 = 0

11 years, 6 months ago.

How about:

float f = 1.2;
int sign = ( f >= (float)0 ) ? 1 : -1;
printf( "sign of %f = %d\n", f, sign );

This is more portable since it doesn't make any assumptions about the representation of ints or floats.