1

I'm trying to convert a string (or a single char) into given number of digits binary string in java. Assume that given number is 5, so a string "zx~q" becomes 01101, 10110, 11011, 10011 (I' ve made up the binaries). However, I need to revert these binaries into "abcd" again. If given number changes, the digits (so the binaries) will change.

Anyone has an idea?

PS: Integer.toBinaryString() changes into an 8-digit binary array.

4
  • 2
    This might be helpful: stackoverflow.com/questions/4211705/binary-to-text-in-java Commented Mar 17, 2013 at 18:44
  • @Tuğcem Oral Try my solution it will help you. Commented Mar 17, 2013 at 19:02
  • @TGMCians given string might not come up with hexadecimal radix, it might contain any ascii character Commented Mar 17, 2013 at 19:09
  • Actually, this post answers half of my problem. But I couldnt decode the generated binary into desired char. Commented Mar 17, 2013 at 21:18

2 Answers 2

2

Looks like Integer.toString(int i, int radix) and Integer.parseInt(string s, int radix) would do the trick.

Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve like this.

To convert abcd to 1010101111001101,

class Demo {
    public static void main(String args[]) {  
        String str = "abcd";
        for(int i = 0; i < str.length(); i++) {
            int number = Integer.parseInt(String.valueOf(str.charAt(i)), 16);
            String binary = Integer.toBinaryString(number);
            System.out.print(binary);
        }
    }
}

To convert the 1010101111001101 to abcd

String str = "1010101111001101";
String binary = Long.toHexString(Long.parseLong(str,2));
System.out.print(binary);

2 Comments

@SirPentor, Integer.parseInt takes radix for second parameter. However, the desired string to convert to given-digited binary might be like "zz~java". "abcd" wasnt a good example.
What if there is a space in between ?

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.