i'm looking @ implementation of java.io
's datainputstream.readlong()
in se6:
private byte readbuffer[] = new byte[8]; public final long readlong() throws ioexception { readfully(readbuffer, 0, 8); return (((long)readbuffer[0] << 56) + ((long)(readbuffer[1] & 255) << 48) + ((long)(readbuffer[2] & 255) << 40) + ((long)(readbuffer[3] & 255) << 32) + ((long)(readbuffer[4] & 255) << 24) + ((readbuffer[5] & 255) << 16) + ((readbuffer[6] & 255) << 8) + ((readbuffer[7] & 255) << 0));
given readbuffer[] array of bytes, why necessary &
each byte 255?
when single byte cast long
, shouldn't remaining bits (9-64) bits of long automatically set zero, rendering &
unnecessary?
java's byte type signed, 0xff (255) == -1, during extending byte int/long - signed value preserved, if have code:
final byte = (byte)0xff; final long b = a; system.out.println(b); // output here -1, not 255
so, here comes 1 trick:
final byte = (byte)0xff; final long b = & 0xff; // binary , between byte , int 0xff system.out.println(b); // output here 255
so, first byte variable promoted int (and became 0xffffffff) because of sign extension, truncate doing bitwise and