Java unsigned byte conversion

Source: Internet
Author: User

The byte type in Java is signed and is worth a range of 128-127

When doing network communication, the received data are often unsigned byte, the range is worth 0-255

So when you convert directly, the values stored in the Java display will be problematic.

int ori=200; System.out.println ("Original byte value:" +ori); byte b= (byte) ori; System.out.println ("byte value in Java:" +B); Integer i=b.intvalue (); System.out.println ("converted int value:" +i); SYSTEM.OUT.PRINTLN ("stored 2 binary values:" +integer.tobinarystring (i)); Integer I_trans=i&0xff; System.out.println ("&0xff after:" +i_trans);

The output is as follows:

Original byte value: Abyte value in Java:- the int value after the conversion:- 2 binary value stored in the number : 11111111111111111111111111001000

For example, to receive an unsigned byte, a value of 200, go to byte in Java, the conversion is 56, so the display is not correct, you need to turn the service number into a signed

The calculation method is to do a & operation with 0xFF, that is, with 11111111 to do A & calculation can

Java unsigned byte conversion

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.