tags:

views:

34

answers:

2

When a float is casted to int, how this casting is implemented by compiler. Does compiler masks some part of memory of float variable i.e., which part of memory is plunked by compiler to pass the remaining to int variable.

I guess the answer to this lies in how the int and float is maintained in memory.

But isn't it machine dependent rather than compiler dependent. How compiler decides which part of memory to copy when casted to lower type (this is a static casting, right).

I am kind of confused with some wrong information, I guess.

(I read some questions on tag=downcasting, where debate on whether it is a cast or a conversion was going on, I am not very much interested on what it is called, as both are performed by compiler, but on how this is being performed).

... Thanks

A: 

When talking about basic types and not pointers, then a conversion is done. Because floating point and integer representations are very different (usually IEEE-754 and two's complement respectively) it's more than just masking out some bits.

If you wanted to see the floating point number represented as an int without doing a conversion, you can do something like this (in C):

float f = 10.5;
int i2 = (int*)&f;
printf("%f %d\n", f, i2);
Rob Neely
Jesse Hall
Good point. Using a union (in C/C++ anyway) is probably the right answer for reinterpreting bits. But it's sort of a useless thing to do anyway, so the question I hope is merely academic! But to the original question, it's really a conversion (changing bit patterns) that's happening when talking about ints and floats.
Rob Neely
@Rob Yes as stated in the question itself, its for understanding purpose only. Anyway your answer helped. Thanks
saurabh
A: 

Most CPU architectures provide a native instruction (or multi-instruction sequence) to do float<->int conversions. The compiler will generally just generate this instruction. There's often faster methods. This question has some good information: http://stackoverflow.com/questions/78619/what-is-the-fastest-way-to-convert-float-to-int-on-x86.

Jesse Hall