Dav*_*ave 11 java byte bit-manipulation operator-keyword
我在项目中有几行代码,我看不到...的价值
buffer[i] = (currentByte & 0x7F) | (currentByte & 0x80);
Run Code Online (Sandbox Code Playgroud)
它从文件中读取文件缓冲区,存储为字节,然后传输到缓冲区[i],如图所示,但我无法理解总体目的是什么,任何想法?
谢谢
正如已经说明的其他答案,(currentByte & 0x7F) | (currentByte & 0x80)相当于(currentByte & 0xFF).JLS3 15.22.1说这被提升为int:
当运算符&,^或|的两个操作数时 是一种可转换(第5.1.8节)到基本整数类型的类型,首先对操作数执行二进制数字提升(第5.6.2节).按位运算符表达式的类型是操作数的提升类型.
因为JLS3 5.6.2说当currentByte有类型byte并且0x7F是int(并且是这种情况)时,则两个操作数都被提升为int.
因此,buffer将是一个元素类型int或更广泛的数组.
现在,通过执行& 0xFFa int,我们有效地将原始byte范围-128..127映射到无符号范围0..255,java.io例如,流经常使用的操作.
您可以在以下代码段中看到此操作.需要注意的是要了解这里发生了什么,你要知道,Java的商店组成的类型,除了char作为2的补值.
byte b = -123;
int r = b;
System.out.println(r + "= " + Integer.toBinaryString(r));
int r2 = b & 0xFF;
System.out.println(r2 + "= " + Integer.toBinaryString(r2));
Run Code Online (Sandbox Code Playgroud)
最后,对于一个真实的例子,查看Javadoc和read方法的实现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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5867 次 |
| 最近记录: |