我正在尝试使用字节将二进制数字字符串压缩到文件中。下面是我尝试通过获取长度为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));
}
关于java - 如何一次将8个字符串转换为单个字节以用Java写入文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36520084/