gpt4 book ai didi

java - Java 中的异或字节

转载 作者:搜寻专家 更新时间:2023-10-31 08:12:04 24 4
gpt4 key购买 nike

Java 不支持对字节的按位操作。我想像这样异或两个字节:

xoredByte = byte1 ^ byte2;

在 java 中,这必须按以下方式完成:

xoredByte = (byte) (byte1 ^ byte2);

编译为:

xoredByte = (byte) ((int)byte1 ^ (int)byte2);

这是否适用于所有情况?我的意思是,这些是等价的陈述吗?

如果不是,执行此操作的代码是什么?

最佳答案

是的,这两种说法是等价的。通常使用二元运算符(包括 ^)时,Java 对两个操作数应用“二进制数字提升”以确保它们至少都是 int 值。 Section 5.6.2 of the JLS包括这个:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  • If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  • Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.

(强调我的)

Binary numeric promotion is performed on the operands of certain operators:

  • The multiplicative operators *, /, and % (§15.17)

  • The addition and subtraction operators for numeric types + and - (§15.18.2)

  • The numerical comparison operators <, <=, >, and >= (§15.20.1)

  • The numerical equality operators == and != (§15.21.1)

  • The integer bitwise operators &, ^, and | (§15.22.1)

  • In certain cases, the conditional operator ? : (§15.25)

(强调我的)

无论是否应用 (int) 转换,byte1byte2 都将被提升为 int 手术前。这也是为什么需要转换回 (byte) 的原因。

关于java - Java 中的异或字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24004579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com