0

I've previously converted a byte array into a file conataining the binary equivalents of all the values in that byte array. Now how do do I convert those binary values back into a byte array??

Like for example...my byte array starts with values 7, 17, 118, 7.... And my text file conatining the binary values shows 00000111000100010111011000000111....

2
  • Why do you convert it to a text file with binary numbers? Commented Jun 3, 2011 at 19:50
  • google "java read binary file into byte array": the first hit (for me) is an example that may be useful for you. Commented Jun 3, 2011 at 20:09

2 Answers 2

2

Read the file 8 characters at a time and use Integer.parseInt(chars, 2) where chars is the 8 characters you read in as a String. Repeat until the file is completely read.

Sign up to request clarification or add additional context in comments.

4 Comments

Yea what you're saying makes sense...but how to read 8 chars at a time? I'm not good at working with files in java. Do i use a FileInputStream?
It's better to use a FileReader, which reads characters instead of bytes. You can then code something like char[] buff = new char[8]; while (rdr.ready()) {int n = rdr.read(buff, 0, 8); /* test that n==8, then process buff */} (If the file contains only the characters '0' and '1', it doesn't actually make a difference, because those characters have one-byte encodings. But it's generally better practice to use a Reader instead of an InputStream when you want characters.)
Okay what I needed was a byte array...so I used Byte.ParseByte(buff,2) . But I'm getting a 'Value out of Range' exception when it is encountering a negative value(the fifth value in the array was -118). What should I do?
The solution is to use (byte) Integer.parseInt(buff, 2). The problem is that "10001010" (-118 as a byte in binary) is not interpreted by Byte.parseByte as a sign bit followed by seven value bits; it is interpreted as a signed number in base 2. So instead of -118, it reads it as +138, which does not fit in a byte. To get -118, it would have to see the string "-1110110".
0

use the input stream

InputStream is = new FileInputStream(new File("filen.ame"));
is.read(byte[] b, 0, len(file))

Input Stream Documentation

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.