java—将字节转换为长字节:为什么有些实现是按位的,每个字节使用0xff?

jjhzyzn0  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(409)

我正在研究 java.ioDataInputStream.readLong() 在se6中:

  1. private byte readBuffer[] = new byte[8];
  2. public final long readLong() throws IOException {
  3. readFully(readBuffer, 0, 8);
  4. return (((long)readBuffer[0] << 56) +
  5. ((long)(readBuffer[1] & 255) << 48) +
  6. ((long)(readBuffer[2] & 255) << 40) +
  7. ((long)(readBuffer[3] & 255) << 32) +
  8. ((long)(readBuffer[4] & 255) << 24) +
  9. ((readBuffer[5] & 255) << 16) +
  10. ((readBuffer[6] & 255) << 8) +
  11. ((readBuffer[7] & 255) << 0));

既然readbuffer[]是一个字节数组,为什么需要 & 每个字节有255?
将单个字节转换为 long ,是否应该将long的剩余位(9-64)自动设置为零,从而呈现 & 不必要?

t9eec4r0

t9eec4r01#

防止带负值字节的符号扩展。

ogsagwnx

ogsagwnx2#

java的字节类型是有符号的,所以0xff(255)==-1,在从byte扩展到int/long的过程中,有符号的值被保留,所以如果您只有代码:

  1. final byte a = (byte)0xff;
  2. final long b = a;
  3. System.out.println(b); // output here is -1, not 255

所以,这里有一个窍门:

  1. final byte a = (byte)0xff;
  2. final long b = a & 0xff; // binary and between byte A and int 0xff
  3. System.out.println(b); // output here is 255

因此,由于符号扩展,第一个字节变量a被提升为int(并成为0xffffff),然后我们通过按位and来截断它

相关问题