繁体   English   中英

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

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

我正在尝试将整数(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);
    }
}

这是我的代码片段,可悲的是它创建了文件但不包含任何数据,但是我的 System.out.format 行确实打印出预期的结果。

0x0 0x0 0x1 0xff

在这种情况下,我只想将第一个字节 (0xff) 以二进制格式写入我的文件。 像这样:

11111111

有人可以指出我可能做错了什么吗?

我会在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