简体   繁体   中英

Assigning int to byte in java?

int val = 233;
byte b = (byte) val;
System.out.println(b);

I have a simple case: I have one integer with some value & I want to convert that value into a byte for output. But in this case, a negative value is coming.

How can I successfully place the int value to byte type?

在Java中, 字节范围是-128到127.您不可能将整数233存储在一个字节中而不会溢出。

Java's byte is a signed 8-bit numeric type whose range is -128 to 127 ( JLS 4.2.1 ). 233 is outside of this range; the same bit pattern represents -23 instead.

11101001 = 1 + 8 + 32 + 64 + 128 = 233 (int)
           1 + 8 + 32 + 64 - 128 = -23 (byte)

That said, if you insist on storing the first 8 bits of an int in a byte, then byteVariable = (byte) intVariable does it. If you need to cast this back to int , you have to mask any possible sign extension (that is, intVariable = byteVariable & 0xFF; ).

You can use 256 values in a byte, the default range is -128 to 127, but it can represent any 256 values with some translation. In your case all you need do is follow the suggestion of masking the bits.

int val =233; 
byte b = (byte)val; 
System.out.println(b & 0xFF); // prints 233.

如果需要无符号值的字节,请使用b&0xFF

Since, byte is signed in nature hence it can store -128 to 127 range of values. After typecasting it is allowed to store values even greater than defined range but, cycling of defined range occurs as follows. cycling nature of range

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