为什么 Java 中的某些字符到字节的转换需要按位 "and"?
Why the need of a bitwise "and" for some char to byte conversions in Java?
我在这里使用 Java 到 C# 的示例应用程序转换,其中涉及密码学(AES 和 RSA 等...)
在 Java 代码(实际工作并被翻译成 C# 的代码)中的某个时刻,我找到了这段代码:
for (i = i; i < size; i++) {
encodedArr[j] = (byte) (data[i] & 0x00FF);
j++;
} // where data variable is a char[] and encodedArr is a byte[]
经过一些谷歌搜索 (here),我发现这是主要在 Java 代码上的常见行为...
我知道 char
是 16 位类型而 byte
只是 8 位类型,但我无法理解 [=15= 的这种按位和操作的原因]转换。
有人可以解释一下吗?
提前致谢。
这是一种通过仅保留最低有效位来截断值的方法,因此它 "fits" 一个字节!
希望对您有所帮助!
当你将 0x00FF 转换为二进制时,它变成 0000 0000 1111 1111
当你和任何带1的东西,它就是它自己:
1 && 1 = 1, 0 && 1 = 0
当你和任何带0的东西都是0
1 && 0 = 0, 0 && 0 = 0
当此操作发生时 encodedArr[j] = (byte) (data[i] & 0x00FF);
它只获取数据的最后 8 位和最后 8 位并存储它。它丢弃前 8 位并存储最后 8
之所以需要这样做是因为一个字节被定义为一个八位值。按位并存在以阻止潜在的溢出 -> IE 将 9 位分配给一个字节
Java 中的一个字符是 2 bytes!该逻辑用于阻止溢出。然而,正如有人在下面指出的那样,这是毫无意义的,因为演员会为你做这件事。可能是有人谨慎了?
在这种情况下,这是完全没有必要的,但是人们在 "just in case" 中放置的那种东西。根据 JLS,5.1.3. Narrowing Primitive Conversion
A narrowing conversion of a char to an integral type T likewise simply
discards all but the n lowest order bits, where n is the number of
bits used to represent type T. In addition to a possible loss of
information about the magnitude of the numeric value, this may cause
the resulting value to be a negative number, even though chars
represent 16-bit unsigned integer values.
加宽转换时通常需要类似的代码来抑制符号扩展。
我在这里使用 Java 到 C# 的示例应用程序转换,其中涉及密码学(AES 和 RSA 等...)
在 Java 代码(实际工作并被翻译成 C# 的代码)中的某个时刻,我找到了这段代码:
for (i = i; i < size; i++) {
encodedArr[j] = (byte) (data[i] & 0x00FF);
j++;
} // where data variable is a char[] and encodedArr is a byte[]
经过一些谷歌搜索 (here),我发现这是主要在 Java 代码上的常见行为...
我知道 char
是 16 位类型而 byte
只是 8 位类型,但我无法理解 [=15= 的这种按位和操作的原因]转换。
有人可以解释一下吗?
提前致谢。
这是一种通过仅保留最低有效位来截断值的方法,因此它 "fits" 一个字节!
希望对您有所帮助!
当你将 0x00FF 转换为二进制时,它变成 0000 0000 1111 1111
当你和任何带1的东西,它就是它自己:
1 && 1 = 1, 0 && 1 = 0
当你和任何带0的东西都是0
1 && 0 = 0, 0 && 0 = 0
当此操作发生时 encodedArr[j] = (byte) (data[i] & 0x00FF);
它只获取数据的最后 8 位和最后 8 位并存储它。它丢弃前 8 位并存储最后 8
之所以需要这样做是因为一个字节被定义为一个八位值。按位并存在以阻止潜在的溢出 -> IE 将 9 位分配给一个字节
Java 中的一个字符是 2 bytes!该逻辑用于阻止溢出。然而,正如有人在下面指出的那样,这是毫无意义的,因为演员会为你做这件事。可能是有人谨慎了?
在这种情况下,这是完全没有必要的,但是人们在 "just in case" 中放置的那种东西。根据 JLS,5.1.3. Narrowing Primitive Conversion
A narrowing conversion of a char to an integral type T likewise simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the resulting value to be a negative number, even though chars represent 16-bit unsigned integer values.
加宽转换时通常需要类似的代码来抑制符号扩展。