如何在Java中将int []转换为ByteBuffer?
发布时间:2020-12-15 08:47:56 所属栏目:Java 来源:网络整理
导读:正如标题所说,我需要在 Java中将int []转换为ByteBuffer.有推荐的方法吗? 我想把ByteBuffer通过JNI传递给C.在这种情况下,对于任何特定的字节序转换,我需要注意什么? 编辑:对不起,我错误地写了ByteArray,但意味着类型ByteBuffer. 编辑:示例代码: 我剥掉
正如标题所说,我需要在
Java中将int []转换为ByteBuffer.有推荐的方法吗?
我想把ByteBuffer通过JNI传递给C.在这种情况下,对于任何特定的字节序转换,我需要注意什么? 编辑:对不起,我错误地写了ByteArray,但意味着类型ByteBuffer. 编辑:示例代码: 我剥掉了不必要的部分.我从c调用JNI上的Java函数来加载资源并将其作为bytebuffer传递回c.它适用于各种其他资源.现在我有一个“int []”,想知道是否有一种优雅的方式将它转换为bytebuffer,或者我必须采用旧式的方式并将其填入for循环中. ByteBuffer resource= null; resource = ByteBuffer.allocateDirect((x*y+2)*4).order(ByteOrder.nativeOrder()); . . ByteBuffer GetResourcePNG(String text) { . . int [] pix; map.getPixels(pix,x,y); return resource; } 解决方法
如果您希望能够使用
JNI’s
GetDirectBufferAddress ,则必须使用
ByteBuffer.allocateDirect .
使用 在正确配置ByteBuffer的字节顺序之后,使用 完整示例: import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; public class Test { static final int bytes_per_datum = 4; public static void main(String args[]) { main2("Native Endian",ByteOrder.nativeOrder()); main2("Big Endian",ByteOrder.BIG_ENDIAN); main2("Little Endian",ByteOrder.LITTLE_ENDIAN); } static void main2(String comment,ByteOrder endian) { int[] data = { 1,0xF,0xFF,0xFFF,0xFFFF,0xFFFFF,0xFFFFFF,0xFFFFFFF,0xFFFFFFFF }; ByteBuffer bb = ByteBuffer.allocateDirect(data.length * bytes_per_datum); bb.order(endian); // endian must be set before putting ints into the buffer put_ints(bb,data); System.out.println(comment + ": "); print(bb); } static void put_ints(ByteBuffer bb,int[] data) { IntBuffer b = bb.asIntBuffer(); // created IntBuffer starts only from the ByteBuffer's relative position // if you plan to reuse this IntBuffer,be mindful of its position b.put(data); // position of this IntBuffer changes by +data.length; } // this IntBuffer goes out of scope static void print(ByteBuffer bb) { // prints from start to limit ByteBuffer bb_2 = bb.duplicate(); // shares backing content,but has its own capacity/limit/position/mark (equivalent to original buffer at initialization) bb_2.rewind(); for (int x = 0,xx = bb_2.limit(); x < xx; ++x) { System.out.print((bb_2.get() & 0xFF) + " "); // 0xFF for display,since java bytes are signed if ((x + 1) % bytes_per_datum == 0) { System.out.print(System.lineSeparator()); } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |