首页 > Java > java教程 > 正文

为什么在 Java 中将 `int` 转换为 `byte` 会导致意外的负结果?

DDD
发布: 2024-11-15 08:42:02
原创
960 人浏览过

Why does casting an `int` to a `byte` in Java lead to an unexpected negative result?

Unexpected Behavior: Java Byte Conversion Interrogation

In Java, when an int is converted to a byte, the unexpected outcome of -124 from the following code snippet has raised eyebrows:

int i = 132;

byte b = (byte)i;
System.out.println(b);
登录后复制

Delving into the Enigma

To unravel this mystery, we must delve into the intricacies of primitive data types in Java. Ints, spanning 32 bits, and bytes, with 8 bits, differ in their storage capacities. Most primitive types, including bytes, are signed, meaning they represent both positive and negative values using two's complement encoding.

Sign Bit Dominance

In two's complement, the most significant bit (MSB) determines the sign. When converting a byte to an int, the MSB is replicated throughout the new MSBs. Hence, an 8-bit byte 255 (11111111) becomes a 32-bit int 111111111111111111111111101010101.

Negative Value Deception

Interpreting negative two's complement numbers involves finding the first MSB from left to right and inverting all subsequent bits. For our int representation of 255 above, this yields 00000000000000000000000001111111 = -1. This explains why Java displays -124, the signed value of 132.

Revealing the Unsigned Truth

To uncover the unsigned value of a byte, we employ a bitmask (0xff) that isolates the least significant 8 bits, removing the superfluous sign bits. Applying this masking operation to the byte signedByte = -1 yields the unsigned value unsignedByte = 255.

Bitwise Magic

Bitwise AND masks off the unnecessary sign bits. When an int is cast to a byte, Java discards the top 24 bits. The masking ensures that the surviving 8 bits are interpreted by Java as a positive value, since the sign bit is now 0.

Unmasking the Byte's Intrigue

This behavior highlights the crucial distinction between signed and unsigned representations of numbers and the bit-level operations at play during data type conversions. By understanding these principles, we can decipher the puzzle of byte conversions in Java and avoid unexpected outcomes.

以上是为什么在 Java 中将 `int` 转换为 `byte` 会导致意外的负结果?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板