简体   繁体   中英

Set greater than 127 int byte variable in java

I write the following sample code:

public static void main(String[] args) throws Exception
{
      byte number_1 =  127;
      byte number_2 =  (byte) 128;
      System.out.println("number_1 = " + number_1);
      System.out.println("number_2 = " + number_2);
}

I get the following result in output:

number_1 = 127
number_2 = -128

I know range of a byte data type( -128 to 127 ). Is my sample is correct? What happened? Is there a two's complement operation? I don't understand this behavior.

Because one byte can hold upto -128 to 127 only, This is expected behavior of overflow

Check with this loop

for(int index = 0 ; index < 258 ; index ++ ){
  System.out.println((byte)index);
}

数字线

Also See

This is because of byte range . A byte can store values from -128 to 127 only.

From the official documentation on primitive datatypes :

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

To respond your question : How to Set greater than 127 int byte variable in java ?

The best way to represent an unsigned byte is to use a signed integer , because the Java VM represents bytes as 32 bits, you're not saving anything by using a byte.

You're seeing the effect of a narrowing primitive conversion : casting the integer literal 128 to a byte results all all but the last byte being thrown out. The last byte of an integer has value 10000000 , which when interpreted in two's complement as a one-byte value comes out to -128 .

In contrast, the same value interpreted as a four-byte value filled with zeroes on the left, ie 00000000 00000000 00000000 10000000 , equals 128 .

Because one byte can hold upto -128 to 127 only, when you transform a int which is more than 127 or less than -127, the java compiler makes the change automatically. In fact, the following statement

byte number_2 =  (byte) 128;

has been changed to

byte number_2 =  (byte) -128;

Once you check out the bytecode using javap, you will find it.

最后一个字节数是127,第一个是-128,所以当数字是128时它变成-128,当数字是129时它变成-127 ..它继续直到它再次达到127然后再循环变成 - 128 ..这就是我所理解的......我希望它清楚......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM