Masious
Masious

Reputation: 430

Writing binary from string to file

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?

Upvotes: 1

Views: 5220

Answers (1)

Boann
Boann

Reputation: 50041

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);

Upvotes: 4

Related Questions