問題描述
我有以下 Java 代碼:
I have the following Java code:
byte value = 0xfe; // corresponds to -2 (signed) and 254 (unsigned)
int result = value & 0xff;
打印時的結果是 254,但我不知道這段代碼是如何工作的.如果 &
運算符只是按位操作,那么為什么它不會產生一個字節而是一個整數呢?
The result is 254 when printed, but I have no idea how this code works. If the &
operator is simply bitwise, then why does it not result in a byte and instead an integer?
推薦答案
它將 result
設置為將 value
的 8 位放入result
的最低 8 位.
It sets result
to the (unsigned) value resulting from putting the 8 bits of value
in the lowest 8 bits of result
.
之所以需要這樣的東西是因為 byte
在 Java 中是一個有符號類型.如果你只是寫:
The reason something like this is necessary is that byte
is a signed type in Java. If you just wrote:
int result = value;
然后 result
將以 ff ff ff fe
值結束,而不是 00 00 00 fe
.更微妙的是,&
被定義為僅對 int
值1 進行操作,所以發生的情況是:
then result
would end up with the value ff ff ff fe
instead of 00 00 00 fe
. A further subtlety is that the &
is defined to operate only on int
values1, so what happens is:
value
被提升為int
(ff ff ff fe
).0xff
是int
文字(00 00 00 ff
).- 應用
&
以產生result
的所需值.
value
is promoted to anint
(ff ff ff fe
).0xff
is anint
literal (00 00 00 ff
).- The
&
is applied to yield the desired value forresult
.
(關鍵是轉換為 int
發生在 應用 &
運算符之前.)
(The point is that conversion to int
happens before the &
operator is applied.)
1嗯,不完全是.如果任一操作數是 long
,&
運算符也適用于 long
值.但不在 byte
上.請參閱 Java 語言規范, 部分15.22.1 和 5.6.2.
1Well, not quite. The &
operator works on long
values as well, if either operand is a long
. But not on byte
. See the Java Language Specification, sections 15.22.1 and 5.6.2.
這篇關于value & 是什么意思?0xff 在 Java 中做什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!