So I've always understood casting means taking the binary of something, and interpreting it as the casted entity (truncating if necessary). However I've noticed in C#, you can take a double, which is a 64bit representation that includes exponent as well as value. You can cast it to a long, which is a 64bit representation of a integer with no exponent. Therefore, it seems to me that if you take a random decimal value (say 10.43245) stored in a double, and cast that to a long, you would get some random number that happens to be whatever that binary turns out to be in a long. However that is not what happens, you simply get the truncated decimal and a value of 10.
Is my definition of casting wrong? Or does c# bend the rules a little bit here to give the programmer moreso what they probably expect from such a cast (I also assume java probably does the same, what about c++?)
Nothing magical about it, but it has to be doing more than just a straight convert of bits. For instance, look at how your would convert a float to a integer in assembly:
[Reference: http://www.codeproject.com/Articles/10679/Convert-Float-to-Int-using-Assembly-Language-Progr]
int ftoi(float flt)
{
int i;
_asm
{
mov eax,flt; //loaded mem to acc
rcl eax,1; //left shift acc to remove the sign
mov ebx,eax; //save the acc
mov edx,4278190080; //clear reg edx;
and eax,edx; //and acc to retrieve the exponent
shr eax,24;
sub eax,7fh; //subtract 7fh(127) to get the actual power
mov edx,eax; //save acc val power
mov eax,ebx; //retrieve from ebx
rcl eax,8; //trim the left 8 bits that contain the power
mov ebx,eax; //store
mov ecx, 1fh; //subtract 17 h
sub ecx,edx;
mov edx,00000000h;
cmp ecx,0;
je loop2;
shr eax,1;
or eax,80000000h;
loop1:
shr eax,1; //shift (total bits - power bits);
sub ecx,1;
add edx,1;
cmp ecx,0;
ja loop1;
loop2:
mov i, eax;
//check sign +/-
sign:
mov eax,flt;
and eax,80000000h;
cmp eax,80000000h;
je putsign;
}
return i;
putsign:
return -i;
}
It's shifting over, then trimming, then subtracting, then shifting again.
In c# cast is an explicit conversion. Section 6 of C# specification 5.0 deals with conversions. In particular section 6.2.1 covers how numerical explicit conversions are defined in the language. As a rule they try to preserve the numerical value being converted as much as it's possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With