Java Essay: Beware of 16 binary negative numbers

Source: Internet
Author: User

Let's see what the following code outputs:

System.out.println (long.tohexstring (0x100000000l + 0xcafebabe));

A long+ a int,int to a long, and then add to the former. It should be 0x1cafebabe right.

The result output is: Cafebabe

Here is a question: 10 int, the plural is represented by a minus sign. What about the 16 binary int?

Yes, the negative number of the 16 binary is the first 1 in the binary representation for negative numbers.

Binary representation of 0xcafebabe: 11001010111111101011101010111110

So, it actually represents a negative number:-889275714

When the corresponding conversion, int to long, the result is: 1111111111111111111111111111111111001010111111101011101010111110

Added to the corresponding 0x100000000l,

1111111111111111111111111111111111001010111111101011101010111110

+ 100000000000000000000000000000000

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

= 11001010111111101011101010111110 (0xcafebabe)

To get the right results, you need to change to:

System.out.println (long.tohexstring (0x100000000l + 0xcafebabeL));

Summarize

When you use 16 to calculate, you need to be aware of negative numbers.

Java Essay: Beware of 16 binary negative numbers

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.