按位与,按位或问题,在Java中 [英] Bitwise AND, Bitwise Inclusive OR question, in Java

查看:116
本文介绍了按位与,按位或问题,在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目中code几行,我看不到的...值

I've a few lines of code within a project, that I can't see the value of...

buffer[i] = (currentByte & 0x7F) | (currentByte & 0x80);

它读取从文件中filebuffer,存储为字节,然后再转移到缓冲区,如图[I],但我不明白,总的目的是什么,什么想法?

It reads the filebuffer from a file, stored as bytes, and then transfers then to buffer[i] as shown, but I can't understand what the overall purpose is, any ideas?

感谢

推荐答案

至于其他的答案已经说过,(currentByte&安培; 0x7F的)| (currentByte&安培; 0x80的)等同于(currentByte&安培;为0xFF)。该JLS3 15.22.1 说,这是晋升为一个 INT

As the other answers already stated, (currentByte & 0x7F) | (currentByte & 0x80) is equivalent to (currentByte & 0xFF). The JLS3 15.22.1 says this is promoted to an int:

在操作的两个操作数和放大器;,
  ^或|是一种类型,是
  转换(§5.1.8)为原始
  整体式,二进制数字
  首先在执行促销
  操作数(§5.6.2)。该类型的
  位运算符前pression是
  推动型操作数。

When both operands of an operator &, ^, or | are of a type that is convertible (§5.1.8) to a primitive integral type, binary numeric promotion is first performed on the operands (§5.6.2). The type of the bitwise operator expression is the promoted type of the operands.

由于JLS3 5.6.2 说,当 currentByte 的类型字节 0x7F的 INT (和是这种情况),那么两个操作数都提升到 INT

because JLS3 5.6.2 says that when currentByte has type byte and 0x7F is an int (and this is the case), then both operands are promoted to int.

因此​​,缓存将元素类型 INT 或更宽的数组。

Therefore, buffer will be an array of element type int or wider.

现在,通过执行&安培; 0xFF的上的 INT ,我们有效地映射原始的字节范围-128..127到无符号范围0..255,操作经常使用的 java.io 流为例。

Now, by performing & 0xFF on an int, we effectively map the original byte range -128..127 into the unsigned range 0..255, an operation often used by java.io streams for example.

您可以通过以下code片段在行动看到这一点。需要注意的是要了解这里发生了什么,你要知道,Java的商店整数类型,除了字符,为的 2的补值。

You can see this in action in the following code snippet. Note that to understand what is happening here, you have to know that Java stores integral types, except char, as 2's complement values.

byte b = -123;
int r = b;
System.out.println(r + "= " + Integer.toBinaryString(r));
int r2 = b & 0xFF;
System.out.println(r2 + "= " + Integer.toBinaryString(r2));

最后,对于一个真实世界的例子,检查出的Javadoc和实施的方法 java.io.ByteArrayInputStream中

/**
 * Reads the next byte of data from this input stream. The value 
 * byte is returned as an <code>int</code> in the range 
 * <code>0</code> to <code>255</code>. If no byte is available 
 * because the end of the stream has been reached, the value 
 * <code>-1</code> is returned. 
 */
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}

这篇关于按位与,按位或问题,在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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