What does value amp; 0xff do in Java?(value amp; 是什么意思?0xff 在 Java 中做什么?)
问题描述
我有以下 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的所需值.
valueis promoted to anint(ff ff ff fe).0xffis anintliteral (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 中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:value & 是什么意思?0xff 在 Java 中做什么?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
