如何将8个字符的字符串一次转换为一个字节,以便在Java中写入文件



我正在尝试使用字节将二进制数字字符串压缩到文件中。下面是我试图通过获取长度为8的子字符串来转换这个字符串,并试图将这8个字符转换为一个字节。基本上每个角色都有一点。请告诉我是否有更好的方法来解决这个问题?我不允许使用任何特殊的图书馆。

编码

public static void encode(FileOutputStream C) throws IOException{
    String binaryString = "1001010100011000010010101011";
    String temp = new String();
    for(int i=0; i<binaryString.length(); i++){
        temp += binaryString.charAt(i);
        // once I get 8 character substring I write this to file
        if(temp.length() == 8){
            byte value = (byte) Integer.parseInt(temp,2);
            C.write(value);
            temp = "";
        }
        // remaining character substring is written to file
        else if(i == binaryString.length()-1){
            byte value = Byte.parseByte(temp, 2);
            C.write(value);
            temp = "";
        }
    }
    C.close();
}

解码

Path path = Paths.get(args[0]);
byte[] data = Files.readAllBytes(path);
for (byte bytes : data){
    String x = Integer.toString(bytes, 2);
}

这些是我正在编码的子字符串:

10010101
00011000
01001010
1011

不幸的是,当我解码时,我得到以下信息:

-1101011
11000
1001010
1011

我将使用以下

public static void encode(FileOutputStream out, String text) throws IOException {
    for (int i = 0; i < text.length() - 7; i += 8) {
        String byteToParse = text.substring(i, Math.min(text.length(), i + 8));
        out.write((byte) Integer.parse(byteToParse, 2));
    }
    // caller created the out so should be the one to close it.
}

打印文件

Path path = Paths.get(args[0]);
byte[] data = Files.readAllBytes(path);
for (byte b : data) {
    System.out.println(Integer.toString(b & 0xFF, 2));
}

检查这是否是您想要的:

Byte bt = (byte)(int)Integer.valueOf("00011000", 2);
System.out.println(bt);
System.out.println(String.format("%8s",Integer.toBinaryString((bt+256)%256)).replace(' ', '0'));

最新更新