1

Currently, I have a String with the value "0100100001101001" (this is binary for the word 'Hi'). I'm trying to figure out how to take that string and convert it back into the word "Hi"

I used

String s = "Hi";   
byte[] bytes = s.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;      
    }         
}   
s = binary.toString();

found on: Convert A String (like testing123) To Binary In Java

Any help would be much appreciated. Thanks in advance.

Community
  • 1
  • 1
  • 6
    *""0100100001101001" (this is binary for the word 'Hi')"* ***In what character set?*** (Yes, I know, ASCII and most others, because it *happens* that "H" and "i" are fairly common amongst them. But the point stands.) – T.J. Crowder Jan 23 '12 at 23:25
  • Why can't you just undo what you have done? – Ingo Jan 24 '12 at 17:02

2 Answers2

2

Something like..

BigInteger val = new BigInteger("0100100001101001", 2);
String hi = new String(val.toByteArray());
Shad
  • 15,134
  • 2
  • 22
  • 34
izb
  • 50,101
  • 39
  • 117
  • 168
  • 3
    +1 It might be appropriate to include an encoding specification when converting bytes to a string; e.g.: `String hi = new String(val.toByteArray(), "UTF-8");`. There's also the small problem of byte ordering, but OP is on his own for this. – Ted Hopp Jan 23 '12 at 23:29
1

Another solution, for variety. Uses (char) casting. Take s to be the binary String:

String result = "";
for (int i = 0; i < s.length(); i += 8) {
    result += (char) Integer.parseInt(s.substring(i, i + 8), 2);
}
calebds
  • 25,670
  • 9
  • 46
  • 74