import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
public class VarHandleExample {
static final byte[] bytes = {0x02, 0x00, (byte) 0xbe, (byte) 0xba, (byte) 0xfe, (byte) 0xca};
private static class FileDesc {
static final VarHandle VH_intArrayView = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);
static final VarHandle VH_shortArrayView = MethodHandles.byteArrayViewVarHandle(short[].class, ByteOrder.LITTLE_ENDIAN);
private final byte[] buf;
int bufPos;
FileDesc(byte[] buf, int headerPosition) {
bufPos = ((short) VH_shortArrayView.get(buf, headerPosition)) + headerPosition;
this.buf = buf;
}
public int getVal() {
return (int) VH_intArrayView.get(buf, bufPos);
}
}
public static void main(String[] args) {
FileDesc fd = new FileDesc(bytes, 0);
System.out.format("The int we get from fd.get() is: 0x%x\n", fd.getVal());
}
}The int we get from fd.get() is: 0xcafebabe
--
You received this message because you are subscribed to the Google Groups "mechanical-sympathy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mechanical-symp...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
public int getInt(byte[]buf, int ix){
return buf[ix] | buf[ix + 1] << 8 | buf[ix + 2] << 16 | buf[ix + 3] << 24;
}