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

Roman C
  • 49,761
  • 33
  • 66
  • 176
CmchPt
  • 41
  • 7
  • Write is as a String. Try http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java and then parse it into binary – jesantana Apr 01 '13 at 13:01
  • out.write( "0001".getBytes() ) – alphazero Apr 01 '13 at 13:01
  • Duplicate of http://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java – TC1 Apr 01 '13 at 13:08

2 Answers2

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);
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
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)

CodeChimp
  • 8,016
  • 5
  • 41
  • 79