简体   繁体   English

Java - 想要将整数值类型转换为字节,以便我可以以二进制格式写入文件

[英]Java - Want to convert an Integer Value type to a Byte, so I can write to a file in binary format

I'm trying to convert an Integer (32 bits or 4 Bytes) to a Byte array and write to a file ONLY the first Byte of that integer truncated.我正在尝试将整数(32 位或 4 字节)转换为字节数组,并仅将截断的整数的第一个字节写入文件。

DataOutputStream os = new DataOutputStream(new FileOutputStream(fileChooser.getSelectedFile() + ".soit"));

byte[] bytes = ByteBuffer.allocate(4).putInt(511).array();
for (byte b : bytes) {
    System.out.format("0x%x ", b);
    try {
        os.write(bytes, 0, 1);
    } catch (IOException ex) {
        Logger.getLogger(p8r_planning.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Here's a snippet of my code, which sadly creates the file but does not contain any data, however my System.out.format line, does print out the expected results.这是我的代码片段,可悲的是它创建了文件但不包含任何数据,但是我的 System.out.format 行确实打印出预期的结果。

0x0 0x0 0x1 0xff 0x0 0x0 0x1 0xff

in this case, I only want the very first byte (0xff) written to my file in binary format.在这种情况下,我只想将第一个字节 (0xff) 以二进制格式写入我的文件。 Like this:像这样:

11111111 11111111

Can someone point to me what I might have done wrong?有人可以指出我可能做错了什么吗?

I would use the writeInt on DataOutputStream which write it as big endian我会在DataOutputStream上使用writeInt将它写为大端

try (DataOutputStream os = new DataOutputStream(
                           new FileOutputStream(
                               fileChooser.getSelectedFile() + ".soit"))) {
   os.writeByte((byte) 511); // write just the lowest 8-bits.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM