簡體   English   中英

如何一次將8個字符串轉換為單個字節以用Java寫入文件?

[英]How to convert 8 character string into a single byte at a time to write to file in 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'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM