我在java中有一个int [],我想转换为byte [].
现在通常的做法是创建一个新的byte [] 4倍大小的int数组,并将所有的int字节逐字节复制到新的字节数组中.
但是,这样做的唯一原因是因为java的类型安全规则.int数组已经是一个字节数组.它只是java不允许将int []转换为byte []然后将其用作byte [].
有没有办法,也许使用jni,使一个int数组看起来像java的字节数组?
不可以.没有能力使用本机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)));
}
}
Run Code Online (Sandbox Code Playgroud)
(以上未经过测试/编译等,取决于您的字节排序要求.这纯粹是说明性的)
| 归档时间: |
|
| 查看次数: |
545 次 |
| 最近记录: |