如何保持写入文件的二进制数据的一致性?

How to maintain consistency in the binary data written to a file?

我正在尝试将二进制字符串写入文件,后记读取它并以十六进制表示形式呈现。这是我的代码:

import java.io.*;
import java.math.BigInteger;

public class TestByte {
      public static void main(String[] argv) throws IOException {

String bin = "101101010110001000010011000000000100010000000001000000000000000100000000000000000000000000000000000010110000000000111111000101010001100000000000000000000000000000001000000000000000000000111110011111000000000010110011";

    //write binary file
    DataOutputStream out = null;
    File fileout = new File("binout.bin");
    out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileout)));
    int indx = 0;
    for (int i = 0; i < bin.length()/8; i++){
        System.out.println(bin.substring(indx, indx+8));
        byte[] bytesout = new BigInteger(bin.substring(indx, indx+8),2).toByteArray();
        out.write(bytesout);
        indx += 8;
    }
    out.close();

    //read binary file
    File filein = new File("binout.bin");       
    byte[] bytesin = new byte[(int) filein.length()];
    FileInputStream inputStream = new FileInputStream(filein);
    inputStream.read(bytesin);
    inputStream.close();

    StringBuilder sb = new StringBuilder();
    for (byte b : bytesin) {
        sb.append(String.format("%02X ", b));
    }
    System.out.println(sb.toString());      
}}

该程序可以运行,但是与数据存在一些不一致。 这是输出:

10110101 01100010 00010011 00000000 01000100 00000001 00000000 00000001 00000000 00000000 00000000 00000000 00001011 00000000 00111111 00010101 00011000 00000000 00000000 00000000 00001000 00000000 00000000 00111110 01111100 00000000 10110011

00 B5 62 13 00 44 01 00 01 00 00 00 00 0B 00 3F 15 18 00 00 00 08 00 00 3E 7C 00 00 B3

如您所见,我已将二进制字符串分解为 8 位的片段,以便更容易跟上数字。不一致是十六进制表示。十六进制字符串的开头似乎多了一个“00”,不应该在那里。字符串末尾还有一个“00”,在"B3".

之前应该只有一个“00”

任何人都可以阐明这个问题 and/or 使解决方案更优雅吗?任何帮助,将不胜感激。谢谢。

你应该像这样使用Integer.parseInt来避免符号/2s补码问题。

这对我有用:

for (int i = 0; i < bin.length()/8; i++){
    System.out.println(bin.substring(indx, indx+8));
    int b = Integer.parseInt(bin.substring(indx, indx+8),2);
    out.writeByte(b);
    indx += 8;
}

另见:Converting a String representation of bits to a byte