views:

59

answers:

2

I want to convert a floating point user input into its integer equivalent. I could do this by accepting an input string, say "-1.234" and then I could just explicitly convert each character to it's decimal representation. (big endian by the way). So I would just say for the example I gave,

-1.234 = 1|01111111|00111011111001110110110

sign bit = 1 = 128<<31
exponent bits = 01111111 = 127<<23
mantissa bits = 00111011111001110110110 = 1962934
decimal equivalent = 1962934 + 127<<23 + 128<<31

This is easy enough but unwieldy. Is there a better way to do this? Maybe some sort of type casting I can do?

+2  A: 

I think that there is a better solution... but here's my one:

float a=-1.234;
int b=*(int*)&a;

I hope I understood you correctly

BlaXpirit
Beautiful, thanks.
Dan Snyder
At least in g++ I'm pretty sure you have to disable strict-aliasing for this to always work.
Mark B
Umm... to be sure you may add some parentheses: int b=*((int*)(
BlaXpirit
+4  A: 

A union lets you access the same piece of memory as different types

union floatint
{
   float f;
   int i;
}

floatint fi;
fi.f=-1.234;
int i=fi.i;

warning: you can get into weird platform differences and things like that because of size and alighnment, but since you're already making some assumptions by trying to interpret the float as an int, you may be able to get away with it. Read more about unions, I think that's what you're going to want.

miked
This is for the "OS" part of my processor simulation that I'm designing in verilog/c++. I designed the processor to stringently follow the MIPSI ISA and I've also defined the architecture to follow the big endian convention so as long as I feed the type of integer equivalent I mentioned, I don't think I have to worry about anything else.
Dan Snyder