Page 1 of 1 [ 3 posts ] 

Fuzzy
Veteran
Veteran

User avatar

Joined: 30 Mar 2006
Age: 52
Gender: Male
Posts: 5,223
Location: Alberta Canada

26 Dec 2008, 9:59 am

I'm looking for an example of a C/C++ or java function that will isolate the positive/negative bit in a float variable.

Obviously I could just use if(), but I like to avoid them, and I like to learn. In C you can use bitwise AND but only with integers. I need to do it with a float.

So if you please, tell me the name of a function that does this, or demonstrate for me in a short sample of code how it may be done. Or both.


_________________
davidred wrote...
I installed Ubuntu once and it completely destroyed my paying relationship with Microsoft.


t0
Veteran
Veteran

User avatar

Joined: 23 Mar 2008
Age: 51
Gender: Male
Posts: 726
Location: The 4 Corners of the 4th Dimension

26 Dec 2008, 10:50 am

What are you really trying to accomplish? IMHO, you should treat the float as an opague object and use something guaranteed to work on all architectures. If you're strongly opposed to if()s (I have no idea why) you could do something like:

fNegative = (flValue < 0.0f) ? TRUE : FALSE;


If you really want to do this, you could cast the float to an array of characters and check the bit. The bit to check will vary based on the byte-order of the hardware.

char * arrchValue = (char *) &flValue;
// use bitwise AND to check the value

In general, it's really poor practice to use these kinds of hacks. If it's commercial software, you're increasing the cost of testing and maintaining your code.

EDIT: bits, bytes, typos, etc



Fuzzy
Veteran
Veteran

User avatar

Joined: 30 Mar 2006
Age: 52
Gender: Male
Posts: 5,223
Location: Alberta Canada

26 Dec 2008, 5:17 pm

Other than it being late when I posted, I dont know why i didnt specify why i was doing it.

I'm calculating a dot product of two vectors to determine if two polygons are heading away from each other. So the negative bit is the important part.

I like conditional assignments better than straight if(), but really, its a fork in programming and if I can skip them for a singular line of code, I want to.

but it still beats casting to an array of bytes, doesnt it?

if there is not a more efficient way than the conditional structure, I will use that. Partly I am questing to learn alternate ways of doing things.

Its just for my own personal use!


_________________
davidred wrote...
I installed Ubuntu once and it completely destroyed my paying relationship with Microsoft.