byte[] bytes = new byte[4];
bytes[0] = (byte) (0xff & version);
bytes[1] = (byte) ((0xff00 & version) >> 8);
bytes[2] = (byte) ((0xff0000 & version) >> 16);
bytes[3] = (byte) ((0xff000000 & version) >> 24); ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(version);
return bb.array();byte[]转int相同的原理,你们说哪个更快啊?(我本来使用ByteBuffer,今天看到上面的方法,所以发了个贴,懒得测试,就求结果撒= =)
bytes[0] = (byte) (0xff & version);
bytes[1] = (byte) ((0xff00 & version) >> 8);
bytes[2] = (byte) ((0xff0000 & version) >> 16);
bytes[3] = (byte) ((0xff000000 & version) >> 24); ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(version);
return bb.array();byte[]转int相同的原理,你们说哪个更快啊?(我本来使用ByteBuffer,今天看到上面的方法,所以发了个贴,懒得测试,就求结果撒= =)
byte[] bytes = new byte[4];
for(int i=0; i<bytes.length; i++) {
bytes[i] = (byte)value;
value >>= 8;
}
与操作显得多此一举
主要原因是第二种方法创建对象,分配数组,时间主要花在这了。如果只考虑核心的数据操作,我相信ByteBuffer更快,因为putInt()方法甚至不需要移位,直接把int的四个字节复制过来就行了。
bytes[0] = (byte) i;
bytes[1] = (byte) (i >> 8);
bytes[2] = (byte) (i >> 16);
bytes[3] = (byte) (i >> 24);
return bytes; ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(i);
return bb.array();移位比ByteBuffer快7-8倍 int i = 0xff & bytes[0];
i |= (bytes[1] << 8) & 0xff00;
i |= (bytes[2] << 16) & 0xff0000;
i |= (bytes[3] << 24) & 0xff000000;
return i; ByteBuffer bb = ByteBuffer.wrap(bytes);
return bb.getInt();移位比ByteBuffer快10-11倍 = =
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >> 8); }
private static byte int0(int x) { return (byte)(x >> 0); }
static void putIntB(ByteBuffer bb, int bi, int x) {
bb._put(bi + 0, int3(x));
bb._put(bi + 1, int2(x));
bb._put(bi + 2, int1(x));
bb._put(bi + 3, int0(x));
}实际上bytebuffer也是移位啊, 而且也是new byte[4], 但是多了一堆参数,还有big endian little endian的判断和一堆继承关系.