1

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
  • Look at operators such as AND, OR, SHR, and SHL. Other than that, what are you asking? If you are asking for a basic tutorial, this is not the appropriate venue, Commented Dec 27, 2014 at 16:13

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

@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.
But I need to put that in my file anyway. Should I add some "0" at the beginning of the string?
@Masious You certainly can, but then the conversion is lossy because it doesn't quite preserve the original string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.