2

I looked for this about an hour now, but couldn't get any advise specific to my problem. What I'd like to do is take a string of 0's and 1's and manipulate a char that it fits the given String pattern. For example:

    char c = 'b'
    String s = "00000000 01100001";

Now I'd like to manipulate the bits in c, so that they match the bit pattern specified in s. As result c would be printed as 'a' (if I'm not completely wrong about it). Any help appreciated!

3 Answers 3

1

You can do

char a = (char) Integer.parseInt("0000000001100001", 2);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks all of you for the instant help! Much appreciated!
1

To do the conversion from binary string to Integer, use parseInt with the 2nd argument as 2.

int temp = Integer.parseInt("01100001", 2);

You can modify with binary operators (&,|,^), but if what you really want is to just assign a variable, you can do it with casts.

char c = 'c';    
System.out.println((char)(c&temp));

System.out.println((char)temp);

Comments

0

How about:

      String s = "00000000 01100001";
      String[] w = s.split(" ");
      char c = (char)(Integer.parseInt(w[0], 2) * 256 + Integer.parseInt(w[1], 2));

This allows for the leading zeroes of each byte to be omitted. If you know they're there, you can just replace the space out of the string and use a single parseInt() call:

      char c = (char)Integer.parseInt(s.replace(" ", ""), 2);

1 Comment

I would have done s.replaceAll(" ", ""); and parseInt that. valueOf might create an object.

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.