价值与价值是什么?在Java中用0xff做什么? [英] What does value & 0xff do in Java?

查看:157
本文介绍了价值与价值是什么?在Java中用0xff做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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?

推荐答案

结果设置为(无符号)值,将8位值放在结果的最低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;

然后结果最终会得到价值 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:


  1. value 升级为 int ff ff ff fe )。

  2. 0xff int 文字( 00 00 00 ff )。

  3. & 用于产生结果的所需值。

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(关键是转换为 int 在 <$ c $之前发生 c>& 运算符已应用。)

(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.

这篇关于价值与价值是什么?在Java中用0xff做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆