Initialization of byte types in Java

Source: Internet
Author: User

Very early due to work needs, touch a little Java, so there is this pit, today back to see themselves in the StackOverflow raised the problem found it, and then recorded.

In use, each bit of byte type needs to be set to 1. I never thought of such a simple operation, there are various constraints in Java.

First look at the code:

// 方式 1byte allBitsOne = 0xFF;
// 方式2byte allBitsOne = (byte)0xFF; 
// 方式3byte allBitsOne = 0xFFFFFFFF; 

Which of the above can achieve the requirement to have each bit of byte type 1? The answer is 2, 3.

Why is mode 1 not possible?

Because in Java, the integer literal (literal integers) is represented by a fixed signed 32-bit integer. The byte type is also a signed 8-bit type in Java, indicating that the range is decimal -128~127 . 0xFFthe decimal represents a 255 range that exceeds the representation of the byte type.

Why is mode 2 possible?

Because 0xFF this 32-bit integer, the low 8 bits are 1, now with a (byte) cast, and discard its extra high, so the remaining 8 bits are 1 of the byte assignment to the left.

Why is mode 3 possible?

Because in Java, the integer literal (literal integers) is represented by a fixed signed 32-bit integer. and is the complement of the form, then for the 0xFFFFFFFF number that it represents the absolute value is 各位按位取反后 + 1 , you can know the absolute value is 1, and the highest level is the sign bit, so that is -1 , and then according to the byte type in Java can be represented -128~127 , so you can assign a value, and -1 in the The byte type is where every bit is 1 .

I think there are two pits:

    1. Why is the byte type designed instead of in Java Int8 UInt8 ?
    2. Java type system is too inflexible to see the literal in Swift

Initialization of byte types in Java

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.