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?
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.
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.
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.
Int to Byte Conversion in Java It means if a value is larger than the byte range, then it gets converted to negative.
In Java byte range is -128 to 127. You cannot possibly store the integer 233 in a byte without overflowing.
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;
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With