Get unsigned numeric values for Java byte

Source: Internet
Author: User
byte a = (byte) 234;
System.out.println (a);

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

If you want to output 234, how do you do it, the first thought is to assign a to a larger type, as follows:

byte a = (byte) 234;	
int i = A;
System.out.println (a);
After execution, or-22, because INT is also signed, so when a is assigned to I, A's sign bit becomes the sign bit of I in I.

The correct approach should be:

byte a = (byte) 234;
int i = A;	
i = a&0xff;
System.out.println (i);

The reason is:

0xFF is int, 4 bytes, A is byte, occupies 1 bytes, the details of the & operation are as follows:

00000000 00000000 00000000 11101010 (a)

&

00000000 00000000 00000000 11111111 (i)

---------------------------------------------------------------------= 00000000 00000000 00000000 11101010

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

In fact, this method in C language can also get signed char unsigned value, but the C language can be directly used to convert unsigned can, than this convenience.



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.