开发者

Primitive DataType Casting in java - Internal Logic

开发者 https://www.devze.com 2023-02-17 10:44 出处:网络
Guys i want to understand , how the widening or narrow implicit casting is internally implemented in java.I know that it involves bit fiddling.

Guys i want to understand , how the widening or narrow implicit casting is internally implemented in java.I know that it involves bit fiddling.

Fo开发者_JAVA百科r example:

//implicit
int i =2400;
long a = (long)i; 

//Explicit  
 float d = (float) 2.23423;

Updates:

I wrote this post after looking at the question posted here Bitshifting to read/write data .Peter Lawrey gave the following answer.

public long create(int one, int two){
    return ((long) one << 32) | (two & 0xFFFFFFFFL);
}

To re-iterate same,widening conversion like above happens at the machine level more or less with smiliar same logic mentioned above by peter.

kindly let me know your valuable comments.


Java uses the IEEE 754 standard machine code instructions supported by your CPU. As such Java does not implement this functionality using something you can break down further.

For conversion from double to float.

  • the sign is preserved
  • exponent is truncated, however if the number is too large it goes to infinity, if to small, it goes to zero.
  • both formats have an implied top bit which is 1, this is unchanged.
  • the top 23 bits of the mantissa is kept (with optional rounding of the 24th bit)

For float to double the process is similar except fields are extended.

However this is all done in the floating point processor unit and Java plays no part in how it happens.


A double has 64 bit, whereas a float has 32 bit. When you cast a double into a float you simply drop the first 32 bits.

Viceversa when you widen you just add as many 0 bits to fill the larger type, for instance you add 32 zeros in fron of the 32 bits of an int to make a long.

0

精彩评论

暂无评论...
验证码 换一张
取 消