## Java Convert Bytes to Unsigned BytesIn Java, byte is data type. It is
byte b = -1; int num = b &0xff //converts byte to unsigned byte in an integer ## Why we need casting (byte to int)?When we need to represent signed numbers in Java, we find 2's complement. In 2's complements the left most bit represent the sign (+ ive or - ive). The bit 0 denotes positive and 1 denotes negative. The rest of the bits denotes the value from -128 to 127. Therefore, it is called 8-bit byte only have 7 bits to store the values. other extra values range from 128 to 255 are unable to fit into a single byte. So, we can cast it to 32-bit unsigned integer for more spaces (bits). ## Byte to Unsigned ByteThe following table depicts the conversion of byte to unsigned byte (int).
## Conversion ProcessFirst, we cast the byte 8-bit into 32-bit. For example, convert -1. Find binary signed 2's complement of -1 by using the following steps: - Write binary of 1, i.e.
**0000 0001** - Invert bits of the binary, i.e.
**1111 1110**. - Add 1 to the inverted bits, i.e.
**1111 1111**
Hence, we get the binary of -1 i.e. Note that when we convert or cast a byte to an int, it increases the bits from 8-bit representation 1111 1111 (-1) Converting 32-bit representation sign extension Now we will get the last 8-bits by performing the &x0ff (bitwise AND). At last, convert binary to decimal. 1111 1111 128+64+32+16+8+4+2+1=255 Therefore -1 is ## Using Java 8 Byte.toUnsignedInt() MethodJava 8 provides the built-in method In an unsigned conversion, the high-order 24 bits of the int are zero and the low-order 8 bits are equal to the bits of the byte argument. Consequently, zero and positive byte values are mapped to a numerically equal int value and negative byte values are mapped to an int value equal to the input plus 2
The method accepts a value to convert to an unsigned int. It returns the argument converted to int by an unsigned conversion.
-8 248 Let's see another approach to convert byte to an unsigned integer.
244 The above program can also be written as follows.
Given Number: -5 251 |

For Videos Join Our Youtube Channel: Join Now

- Send your Feedback to [email protected]