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.

tugcem
  • 1,078
  • 3
  • 14
  • 25
  • 2
    This might be helpful: http://stackoverflow.com/questions/4211705/binary-to-text-in-java – SpaceCowboy Mar 17 '13 at 18:44
  • @Tuğcem Oral Try my solution it will help you. – Ajay S Mar 17 '13 at 19:02
  • @TGMCians given string might not come up with hexadecimal radix, it might contain any ascii character – tugcem Mar 17 '13 at 19:09
  • Actually, [this](http://stackoverflow.com/questions/917163/convert-a-string-like-testing123-to-binary-in-java) post answers half of my problem. But I couldnt decode the generated binary into desired char. – tugcem Mar 17 '13 at 21:18

2 Answers2

2

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

SirPentor
  • 1,994
  • 14
  • 24
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);
Ajay S
  • 48,003
  • 27
  • 91
  • 111
  • @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. – tugcem Mar 17 '13 at 19:02
  • What if there is a space in between ? – user2387900 Oct 20 '13 at 19:08