Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning int to byte in java?

Tags:

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?

like image 457
ramkumar Avatar asked Mar 27 '10 15:03

ramkumar


People also ask

How do you assign an int to a byte in Java?

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.

Can we assign int value to byte?

It's not possible. A byte is 0 to 255. An int is a whole lot bigger than that. So, you can convert an int to a stream of bytes, but not to a byte.

How do I convert an int to a byte?

An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.

What does casting an int to a byte do in Java?

Int to Byte Conversion in Java It means if a value is larger than the byte range, then it gets converted to negative.


2 Answers

In Java byte range is -128 to 127. You cannot possibly store the integer 233 in a byte without overflowing.

like image 123
Darin Dimitrov Avatar answered Oct 16 '22 05:10

Darin Dimitrov


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;).

like image 35
polygenelubricants Avatar answered Oct 16 '22 05:10

polygenelubricants