2

Say I have a binary string ("0 and 1s") and I want to write this string to a binary file, how can this be done in java? I tried converting to ASCII values string, then create a ByteArrayInputStream from that but values over 127 do not display correctly. Can anyone help me with this? My binaryToAscii method:

public static String BinaryToAscii(String bin){
    int num_of_bytes = bin.length()/8;
    StringBuilder sb = new StringBuilder();
    int index = 0;
    String byte_code;
    Character char_code;
    for (int i =0; i<num_of_bytes;i++){
        index = i*8;
        byte_code = bin.substring(index,index+8);
        int charCode = Integer.parseInt(byte_code, 2);
        char_code = new Character((char)charCode);
        sb.append(char_code);
    }
    return sb.toString();
}

Then I convert the returned string to a ByteArrayInputStream using

InputStream is = new ByteArrayInputStream(ascii.toString().getBytes());

3
  • 1
    Instead of thank you notes please show example of what you have as input and what you want as output. Also showing code you've tried would make positive impression... Commented Jan 15, 2013 at 2:12
  • your method should not return String, it should return a byte[] Commented Jan 15, 2013 at 2:34
  • got it working with the bitwise operators, thank you alex Commented Jan 15, 2013 at 22:59

2 Answers 2

1

you first would transform the 0 / 1 string to a byte[].

then write out using

DataOutputStream.writeByte().

read in with
DataInputStream.readUnsignedByte() // to get 0 - 255
Sign up to request clarification or add additional context in comments.

9 Comments

How would I convert the string to a byte[]? Is values that is over 127 going to cause problems?
no not getBytes, you dont want to have a String to byte[] conversion. you want a 0/1 string to byte representarion conversion
instead od Stringbuilder add the int read in line Integer.parseInt to an int ( or byte) array.
What method do you use to convert an integer to byte[] and keep the binary representation?
|
1

To convert string to binary use this: You will first need to break the string into its individual letters then run them through this one at a time.

char letter = c;
  byte[] bytes = letter.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println(binary);

1 Comment

i'm not sure where to go with this

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.