Soapy
Soapy

Reputation: 567

How does this code find the sign of a float

So I stumbled across similar code while researching. I understand that the code will return 0 for a positive float or return 1 for a negative float.

int sign;
sign = ((int)(((long)(13.37f) & 0x80000000L) >> 31));    // sign = 0
sign = ((int)(((long)(-13.37f) & 0x80000000L) >> 31));   // sign = 1

How does casting to a long and bit shifting 31 time right achieve this?

Upvotes: 0

Views: 136

Answers (2)

Dimitri Mockelyn
Dimitri Mockelyn

Reputation: 1545

The first bit of an integer is a sign bit : 1 means that the value is negative, 0 means positive.

This whole operations is just meant to get the first bit of the integer

What this operation does is :

  • A logic & operation between your float and 1000000... (Binary representation of 0x80000000), that returns 000000000000... or 100000000...
  • 31 Shift to get only the first bit : 1 or 0, representing the sign

Upvotes: 2

Cantfindname
Cantfindname

Reputation: 2148

In effect it returns the 1st bit of the 32-bit binary representation of the operand, which is the sign bit of float numbers.

Upvotes: 2

Related Questions