java type casting,Java - TypeCasting问题

long a = (long)Math.pow(2, 32);

// a = 4294967296 :)

long a = (int)(long)Math.pow(2, 32);

//a = 0 ?!

long a = (int)Math.pow(2, 32);

//a = 2147483647 WTF??!!!

The first expression is obvious. a is printed as it is.

The second expression is a bit confusing. The large value is

100000000000000000000000000000000 // 1 followed by 32 ZEROs, 33 bits in all

When it is forced into an int, how is it taken as ZERO? Shouldn't it take the most significant 1 as sign bit and think that the number is -2147483648 ? [DOUBT CLEARED]

Also, when the double returned from Math.pow (4.294967296E9) is directly cast into int, why is it 2147483647?

I am reading up type casting and data types from a book but the text doesn't explain much. I am confused. Please explain why the second and third expression produce those results.

解决方案

No, since it truncates everything past the first 32 bits as far as I know -- so it has no idea about the 1 at the beginning (or rather, at the end).

4294967296 = 0x100000000 (in hexadecimal), and taking only the first 32 bits gives you zero.

Edit: I actually think the other one has to do with a special cast from floating-point to int, that's not the same as going through a long and then an int, since it's a completely different kind of cast to the processor.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值