Rules for converting int to byte in Java

Source: Internet
Author: User

1 ).

A (-| +) 256 = C;

If a is positive, use a-256 = C. If a is negative, use a + 256 = C.

If the result C is not in-128 ~ Between 127, use C (-| +) 256 and so on

Result c is in-128 ~ Examples between 127:

Int number = 200;

200-256 =-56 byte Result 56 is in-128 ~ Between 127

Number =-200;

-200 + 256 = 200 byte result-56 in-128 ~ Between 127

 

Number = 500;

500-256 = 244 244 not in-128 ~ Between 127

244-256 =-12-12 in-128 ~ Between 127

 

2 ).

Example: int number = 500;

First convert the number to binary and then the last eight digits
If the maximum number of digits is not equal to 1, convert the obtained binary data.
The result is obtained in decimal format. If the maximum number of digits is 1
That uses this formula to calculate the decimal number of the binary number.

The converted byte result is obtained from the decimal number-256:

 

The same is true for the hexadecimal or octal format!

 

Example:

Number = 500

Because Int Is 32 bits and byte is 8 bits

500 binary: 0000 0000 0000 0000 0000 0001 1111 0100

Take the last eight bits: 1111 0100 and convert it to 244 in decimal format (the highest bits here is equal to 1)

244-256 =-12 so convert 500 to byte as-12

 

Number = 300

200 binary: 0000 0000 0000 0000 0000 0001 0010 1100

Take the last eight bits: 0010 1100 and convert it to decimal (the highest bits here is not equal to 1 ).

Result: 44

 

Http://j2ee-yohn.javaeye.com/blog/269734

 

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.