I have a string in my code that has a bunch of 0s and 1s. Now I want to make a file from this string that the bits inside, are characters of this string. How can I do it?
1 Answer
This function will decode the binary string to a byte array:
static byte[] decodeBinary(String s) {
if (s.length() % 8 != 0) throw new IllegalArgumentException(
"Binary data length must be multiple of 8");
byte[] data = new byte[s.length() / 8];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '1') {
data[i >> 3] |= 0x80 >> (i & 0x7);
} else if (c != '0') {
throw new IllegalArgumentException("Invalid char in binary string");
}
}
return data;
}
Then you can write the byte array to a file with Files.write (or an OutputStream):
String s = "0100100001100101011011000110110001101111"; // ASCII "Hello"
byte[] data = decodeBinary(s);
java.nio.file.Files.write(new File("file.txt").toPath(), data);
3 Comments
Boann
@Masious It rejects strings containing a number of bits that is not divisible by 8, because you can't represent those in files, because files are a whole number of bytes long, and each byte is 8 bits.
Masious
But I need to put that in my file anyway. Should I add some "0" at the beginning of the string?
Boann
@Masious You certainly can, but then the conversion is lossy because it doesn't quite preserve the original string.