Assigning int to byte in java?

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

I have a simple case: I have a single integer with some value, and I want to convert this value to byte for output. But in this case a negative value comes.

How can I successfully assign an int to a byte?

+6
java
source share
5 answers

In Java byte, the range is from -128 to 127. You cannot store an integer 233 in a byte without overflow.

+14
source share

Java byte is a signed 8-bit numeric type with a range of -128 to 127 ( JLS 4.2.1 ), 233 is out 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) 

However, if you insist on storing the first 8 bits of int in a byte, then byteVariable = (byte) intVariable does this. If you need to return this value to int , you must mask any possible sign extension (i.e. intVariable = byteVariable & 0xFF; ).

+14
source share

You can use 256 values ​​in bytes, the default range is from -128 to 127, but it can represent any 256 values ​​with some translation. In your case, all you need is to follow the bit masking suggestion.

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

If you need an unsigned byte value, use b&0xFF .

+5
source share

Since the byte is signed by nature, it can store a range of values ​​from -128 to 127. After type casting, it is allowed to store values ​​that even exceed a given range, but the cyclicity of a certain range occurs as follows. range nature

0
source share

All Articles