3 Replies Latest reply: Nov 9, 2009 1:34 PM by 843789

# Binary Strings

Im trying to follow this tutorial - http://www.ai-junkie.com/ga/intro/gat3.html

It represents the following values as binary strings e.g:-

1 = 0001
e.t.c
9 = 1001
* = 1100

I can have worked out how to convert integers to binary string and visa versa,
``````for(int i =0;i<10;i++){
System.out.println(Integer.toBinaryString(i));
}``````
however I cant convert chars to binary of visa versa

I have tried the folling buts its not working
``System.out.println(Byte.parseByte("1010" , 2));``

Calypso
• ###### 1. Re: Binary Strings
calypso wrote:
I have tried the folling buts its not working
Never, ever tell us simply that "it's not working." That's a waste of our time. Instead tell us what you expect it to do, and what it's actually doing.
``System.out.println(Byte.parseByte("1010" , 2));``
What does this output, and what do you expect it to output? For me it outputs 10, and I expect it to output 10.

By the way, there's an equivalent method for Short, Integer and Long which will be useful if the value exceeds what can be stored in a byte.
• ###### 2. Re: Binary Strings
>
What does this output, and what do you expect it to output? For me it outputs 10, and I expect it to output 10.
>

In this tutorial, it is stated that

"+" is equal to 1010

How can I convert "+" --> 1010

and

how can I convert 1010 --> "+"

Thanks

Calypso
• ###### 3. Re: Binary Strings
calypso wrote:
>
What does this output, and what do you expect it to output? For me it outputs 10, and I expect it to output 10.
>
{noformat}
In this tutorial, it is stated that

"+" is equal to 1010

How can I convert "+" --> 1010

and

how can I convert 1010 --> "+"
{noformat}
Well, you certainly didn't obtain "1010" by passing in a plus-sign to any method/Constructor of Integer, so I would suggest that you reverse whatever process you used to get 1010 in the first place.

A simple method would be to use a map:
``````Map<Character, String> toBinary = new HashMap<Character, String>();
Map<String, Character> fromBinary = new HashMap<Character, String>();

{
toBinary.put('9', "1001");  fromBinary.put("1001", '9');
toBinary.put('+', "1010"); fromBinary.put("1010", '+');
}

public String encode(char c) {