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
. 0xFF
the 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:
- Why is the byte type designed instead of in Java
Int8
UInt8
?
- Java type system is too inflexible to see the literal in Swift
Initialization of byte types in Java