0

我想将 ByteBuffer 作为 Little Endian 导出到文件中,但是当我再次读取文件时,我必须将其作为 Big Endian 读取才能获得正确的值。如何以可以在创建的文件中读取为 Little Endian 并获得正确值的方式导出 ByteBuffer?

    //In the ByteBuffer tgxImageData there are the bytes which I want to export and import again, the ByteBuffer is ordered as little endian


    //export ByteBuffer into File
    FileOutputStream fos = new FileOutputStream(outputfile);            
    tgxImageData.position(0);
    byte[] tgxImageDataByte = new byte[tgxImageData.limit()];
    tgxImageData.get(tgxImageDataByte);         
    fos.write(tgxImageDataByte);            
    fos.close();


    //import File into ByteBuffer
    FileInputStream fis2 = new FileInputStream(outputfile);     
    byte [] arr2 = new byte[(int)outputfile.length()];
    fis2.read(arr2);
    fis2.close();           
    ByteBuffer fileData2 = ByteBuffer.wrap(arr2);


    fileData2.order(ByteOrder.LITTLE_ENDIAN);           
    System.out.println(fileData2.getShort(0));          //Wrong output, but here should be right output
    fileData2.order(ByteOrder.BIG_ENDIAN);          
    System.out.println(fileData2.getShort(0));          //Right output, but here should be wrong output
4

1 回答 1

0

这是一个如何将 shorts 写为 little endian 的示例

    FileOutputStream out = new FileOutputStream("test");
    ByteBuffer bbf = ByteBuffer.allocate(4);
    bbf.order(ByteOrder.LITTLE_ENDIAN);
    bbf.putShort((short)1);
    bbf.putShort((short)2);
    out.write(bbf.array());
    out.close();

你需要在你的代码中做类似的事情

于 2013-04-18T09:31:12.907 回答