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.

2
  • 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.) Commented Jan 23, 2012 at 23:25
  • Why can't you just undo what you have done? Commented Jan 24, 2012 at 17:02

2 Answers 2

2

Something like..

BigInteger val = new BigInteger("0100100001101001", 2);
String hi = new String(val.toByteArray());
Sign up to request clarification or add additional context in comments.

1 Comment

+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.
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);
}

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.