Maison  >  Article  >  Java  >  Pourquoi la conversion d'un « int » en « octet » en Java conduit-elle à un résultat négatif inattendu ?

Pourquoi la conversion d'un « int » en « octet » en Java conduit-elle à un résultat négatif inattendu ?

DDD
DDDoriginal
2024-11-15 08:42:02960parcourir

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn