使用Python导出基于二进制的文件

2024-04-29 08:58:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在为Blender编写一个导出脚本,但是我觉得我的问题更多的是基于Python的,所以我把它贴在这里。在

一个朋友用java为.obj文件创建了一个转换程序,该程序将文件转换为自定义的二进制文件格式。但是,我想跳过这个过程,直接从Blender导出二进制文件。在

该文件包含文本、整数和浮点,使用utf-8、utf-16和utf-32格式。在

到目前为止,我已经将所有数据导出为标准文本文件,所以我只需要以适当的编码/格式输出它。以下是他在Java中用不同的编码将数据写入文件的代码:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class StreamConverter {

//---------------------------------------------------

public static void buffer_write_string(DataOutputStream out,String text) throws IOException{
    byte[] bytes = text.getBytes();
    for(int i =0;i<text.length();i++){
        buffer_write_u8(out,bytes[i]);
    }
}

public static void buffer_write_u32(DataOutputStream out,int i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putInt(i);
    out.write(b.array());       
}

public static void buffer_write_u16(DataOutputStream out,int i) throws IOException{
    out.write((byte) i);
    out.write((byte) (i >> 8));     
}

public static void buffer_write_s16(DataOutputStream out,int i) throws IOException{
    out.write((byte) i);
    out.write((byte) (i >> 8));     
}

public static void buffer_write_s32(DataOutputStream out,int i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putInt(i);
    out.write(b.array());
}

public static void buffer_write_u8(DataOutputStream out,int i) throws IOException{
    out.writeByte((byte) i);
}

public static void buffer_write_s8(DataOutputStream out,int i) throws IOException{
    out.writeByte((byte) i);
}

public static void buffer_write_f64(DataOutputStream out,double i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(8);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putDouble(i);
    out.write(b.array());

}

public static void buffer_write_f32(DataOutputStream out,float i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putFloat(i);
    out.write(b.array());
}

}

我不知道怎么做这是Python,我试着看看是否至少能让整数正确输出,但没有运气。在

^{pr2}$

用法示例:

write_u32(file, u'%i' % (vertex_count))

也尝试过:

counts = bytes([vertex_count,tex_count,normal_count])
file.write(counts)

我对整个二进制/编码有点迷茫,我已经通读了Python文档,但是没有帮助。在

太好了!在


Tags: importbufferstaticjavabytepublicoutwrite