The solution to the unsigned problem in Java

In Java, there is no Unsigned unsigned data type, but Unsigned conversion can be done easily.

 

Solution 1: If you perform Stream data processing in Java, you can use the DataInputStream class to read the data in the Stream as Unsigned.

 

 Java provides support in this regard. You can use java.io.DataInputStream class objects to complete the Unsigned reading of the data in the stream. This class provides the following methods:

 

         (1) int readUnsignedByte() //Read a single byte data of 0~255 (0xFF) from the stream, and return it as int data type data. The returned data is equivalent to the so-called "BYTE" in the C/C++ language.

 

         (2) int readUnsignedShort() //Read a double-byte data of 0~65535 (0xFFFF) from the stream, and return it as int data type data. The returned data is equivalent to the so-called "WORD" in the C/C++ language and is returned in the form of "low address low byte", so the programmer does not need additional conversion.

 

Scheme 2: Use Java bit operators to complete Unsigned conversion.

 

       Under normal circumstances, the data types provided by Java are signed types, and their corresponding unsigned values ​​can be obtained through bit operations. See the codes in several methods:

 

      public int getUnsignedByte (byte data){ //Convert data byte data to 0~255 (0xFF is BYTE).
         return data&0x0FF;

      }

 

      public int getUnsignedByte (short data){ //Convert data byte data to 0~65535 (0xFFFF is WORD).
            return data&0x0FFFF;

      }       

 

     public long getUnsignedIntt (int data){ //Convert int data to 0~4294967295 (0xFFFFFFFF is DWORD).
         return data&0x0FFFFFFFFl;

      }

 

Using these techniques flexibly, there is no argument that "binary is not fully supported in Java"!

Guess you like

Origin blog.csdn.net/sinat_27674731/article/details/113736046