Reputation: 1108
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.
Upvotes: 1
Views: 12432
Reputation: 48602
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);
Upvotes: 0
Reputation: 2044
Looks like Integer.toString(int i, int radix)
and Integer.parseInt(string s, int radix)
would do the trick.
Upvotes: 2