Processing of unsigned types in Java [go]

Source: Internet
Author: User
Tags bitwise

In Java, there is no unsigned unsigned data type, but you can easily complete the unsigned conversion.

    • Scenario One: If you are streaming (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 by using the Java.io.DataInputStream class object to complete the unsigned reading of data in the stream, which provides the following methods:
(1) int readunsignedbyte ()//reads one 0~255 (0xFF) of single byte data from the stream and returns it as data of the int data type. The returned data corresponds to the so-called "BYTE" in the C + + language.
(2) int readunsignedshort ()//reads a 0~65535 (0xFFFF) Double-byte data from the stream and returns it as data of the int data type. The returned data is equivalent to the so-called WORD in the C + + language and is returned in a low-address low-byte manner, so the programmer does not need an additional conversion.

    • Scenario Two: Use the Java bitwise operator to complete the unsigned conversion.

Normally, the data types provided by Java are of the signed signed type, and the unsigned values corresponding to them can be obtained by bitwise operation, see the code in several methods:

 Public intGetunsignedbyte (byteData) {//converts the data byte type to 0~255 (0xFF, or byte).     returnData&0x0ff;} Public intGetunsignedbyte ( ShortData) {//converts the data byte type to 0~65535 (0xFFFF is WORD).     returnData&0x0ffff;} Public LongGetunsignedintt (intData) {//converts the int data to 0~4294967295 (0xFFFFFFFF is DWORD).     returnData&0x0ffffffffl;}

Flexible use of these techniques, there is no "binary in Java can not get full support" argument!

Processing of unsigned types in Java [go]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.