Returns the unsigned value of a Java byte.

Source: Internet
Author: User
Byte A = (byte) 234; system. Out. println ();

The aboveCodeThe result is-22 because byte in Java is signed and the byte range is-128 ~ 127.

If you want to output 234, what should you do? First of all, assign a to a larger type, as shown below:

 
Byte A = (byte) 234; system. Out. println (a); int I = A; system. Out. println ();

After execution, it is still-22. Because Int Is also signed, when a is assigned to I, the sign bit of a becomes the sign bit of I in I.

The correct method should be:

 
Byte A = (byte) 234; system. out. println (a); int I = A; system. out. println (a); I = A & 0xff; system. out. println (I );

The reason is:

0xff is int, which occupies 4 bytes and A is byte, which occupies 1 byte. The operation details are as follows:

00000000 00000000 00000000 11101010 ()

&

00000000 00000000 11111111 11111111 (I)

---------------------------------------------------------------------

= 00000000 00000000 00000000 11101010

The result is an int, But the sign bit is 0, indicating a positive number, and finally a positive integer of 234.

In fact, this method can also obtain the unsigned value of the signed Char in the C language, but in the C language, you can directly use unsigned for conversion, which is more convenient than this.

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.