Possible Duplicate:
Binary to text in Java
I'm writing a program that can convert multiple things, but I need help with the converting of binary. I have my code for text-to-binary working, but I'm not sure about binary-to-text. Here is my code for the button which triggers the conversion:
String code = jTextArea5.getText();
if (code == null) {
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.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(' ');
}
jTextArea5.setText("" + binary);
}
else
{
System.out.println(jTextArea1.getText( ));
String binary = jTextArea1.getText();
int ascii = Integer.parseInt(binary, 2);
char character = (char)ascii;
jTextArea5.setText("" + character);
}
If anyone knows how I can fix this code to work, that'd be great. Thanks!
NOTE - This bit below works on it's own, just not in conjunction with any efforts to allow converting binary in jTextArea5 to text in jTextArea1.
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.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(' ');
}
jTextArea5.setText("" + binary);