我在java中有一个int[],我想把它转换成byte[]。
现在,通常的方法是创建一个4倍于整数数组大小的新byte[],并将所有int逐字节复制到新的字节数组中。
然而,这样做的唯一原因是因为java的类型安全规则。int数组已经是字节数组。只是java不允许将int[]转换为byte[],然后将其用作byte[]。
有没有办法,比如使用jni,让int数组在java中看起来像一个字节数组?
发布于 2009-08-24 06:45:16
不是的。没有使用原生Java数组接口实现对象的功能。
在我看来,您需要一个包装int[]的对象,并以字节数组的方式提供访问它的方法。例如:
public class ByteArrayWrapper {
private int[] array;
public int getLength() {
return array.length * 4;
}
public byte get(final int index) {
// index into the array here, find the int, and then the appropriate byte
// via mod/div/shift type operations....
int val = array[index / 4];
return (byte)(val >> (8 * (index % 4)));
}
}
(以上代码未经过测试/编译等,并取决于您的字节排序要求。这纯粹是说明性的)
发布于 2009-08-25 06:48:58
根据您的具体要求,您可以使用NIO的java.nio.ByteBuffer
类。作为ByteBuffer进行初始分配,并使用它的getInt
和putInt
方法访问int值。当您需要访问以字节为单位的缓冲区时,可以使用get
和put
方法。ByteBuffer还有一个asIntBuffer
方法,它将默认的get和put行为更改为int而不是byte。
如果你正在使用JNI,直接分配的ByteBuffer (在某些情况下)允许在你的C代码中直接指针访问。
http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html
例如,
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
// …
int[] intArray = { 1, 2, 3, 4 };
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(intArray);
byte[] byteArray = byteBuffer.array();
发布于 2009-08-24 07:45:02
如果你真的必须这样做,你可以在C中使用外部调用来做这件事,但我非常确定这不能在语言中完成。
我也很好奇现有的代码是什么样子的,以及您期望的额外速度有多快。
你知道优化的规则,对吧?
< code >H193b)重新测试,如果您的优化代码未通过速度测试,请在注释中还原!< code >H210
https://stackoverflow.com/questions/1322819
复制