1.

Convert an UNSIGNED byte to Java type

Answer»

When a byte is converted to another data type, it is always considered to be signed. In ORDER for unsigned byte conversion, we must mask it to Java and cast it to an integer.

Firstly, we declare three byte values b1, b2 and b3 and assign them values in the range of -128 to 127. Then we cast the value to an integer and use a logical & operator with 0xFF which represents the HEXADECIMAL number having integer value 255 or has binary representation as 00000000000000000000000011111111 (under the 32-bit integer) and it along with the bitwise effectively masks the VARIABLE leaving its values in the last 8 bits and ignores the other values as the other bits become 0.Thus & 0xff is used for masking variables.

Let us see how an unsigned byte is converted to a Java type:

import java.util.*; public class Example {   public static void main(String[] args)   {      byte b1 = 127;      byte b2 = -128;      byte b3 = -1;      System.out.print(b1+" : ");      System.out.println((int) b1 & 0xFF);      System.out.print(b2+" : ");      System.out.println((int) b2 & 0xFF);      System.out.print(b3+" : ");      System.out.println((int) b3 & 0xFF);   } }

The output is as follows:

$javac Example.java $java  Example 127 : 127 -128 : 128 -1 : 255


Discussion

No Comment Found