由于 29 位整数在 AMF 中很流行,我想合并已知的最快/最好的例程。我们的库中当前存在两个例程,可以在 ideone 上进行实时测试
http://ideone.com/KNmYT
这是快速引用的来源
public static int readMediumInt(ByteBuffer in) {
ByteBuffer buf = ByteBuffer.allocate(4);
buf.put((byte) 0x00);
buf.put(in.get());
buf.put(in.get());
buf.put(in.get());
buf.flip();
return buf.getInt();
}<p></p>
<p>public static int readMediumInt2(ByteBuffer in) {
byte[] bytes = new byte[3];
in.get(bytes);
int val = 0;
val += bytes[0] * 256 * 256;
val += bytes[1] * 256;
val += bytes[2];
if (val < 0) {
val += 256;
}
return val;
}
</p>
最佳答案
通常我会通过位运算来完成此操作。第二个版本最终可能会被 JVM 优化到接近此的程度,但无法确定。现在,按照您的示例,这只是 24 位,但问题是“29 位整数”。我不确定你真正想要哪个。
public static int readMediumInt(ByteBuffer buf) {
return ((buf.get() & 0xFF) << 16)
| ((buf.get() & 0xFF) << 8)
| ((buf.get() & 0xFF);
}
关于java - Java 中字节数组到 29 位整数的最快且最有效的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3670172/