0

How can i write to a file a binary number without it to cut the zeros .

I'm writing like this :

byte[] b = new BigInteger("1011010101010110", 2).toByteArray();

FileOutputStream fos = new FileOutputStream("file",true);
fos.write(b);

But then for example : When i write 0000001, it writes in the file just 1 and ignores the zeros, the same happens if i write 001001001000 , it ignores the zeros on the left reading 8bits at the time from the right to the left.

What is the correct way to write binary digits to a file ? If this is the correct way, i'm might be trying to read the file in the wrong way ( I'm using the read() of InputStream )

Ps-(8 digits must be 1 byte so writing as a string is not an option, cause each digit is 1 byte.)

3

2 Answers 2

1

You can try something like this

    String s = "0000001";
    byte[] a = new byte[s.length()];
    for (int i = 0; i < s.length(); i++) {
        a[i] = (byte) (s.charAt(i) & 1);
    }
Sign up to request clarification or add additional context in comments.

4 Comments

But like that, it takes me 7 bytes to write it one the file.. "0000001" must take only 1 byte.
But you said 'When i write 0000001, it writes in the file just 1 and ignores the zeros'
Yes I know, but there is no way to saving the 0000001 in 1 byte ? without loosing the zeros ?
When you save a byte you always save all 8 bits with leading 0s if any. You need a hex viewer to see all bits.
0

You don't want to write it as a binary, you want to write it as a String representing the binary. The problem is that Java has no way to know you want it padded. I would suggest converting your binary numbers to a String, then left-padding with 0 (Apache StringUtils will help with this)

Comments

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.