Converting Binary

• 03-20-2013, 07:36 PM
Wizard0860
Converting Binary
So I have to make an extension to a program where when the convert button is pressed, the binary will change into a number from 1-255.

So far, I have the following for this specific part. No idea how to convert.

Code:

```public Display10()       {         setLayout(new GridLayout(1, 8));         bits = new JLabel[8];         for(int x = 0; x < bits.length; x++)         {             bits[x] = new JLabel("", SwingConstants.CENTER);             bits[x].setFont(new Font("Serif", Font.BOLD, 50));             add(bits[x]);         }         randomize();       }```
The following is the convert method which I have done so far.

Code:

```public void convert()       {         String[] converter=new String[bits.length];         for(int i=0;i<bits.length;i++)             converter[i] = bits[i].getText();       }```
• 03-20-2013, 10:23 PM
sehudson
Re: Converting Binary
Is your randomize() method responsible for setting the text in each of your JLabels in the bits[] to a "0" or "1"?
• 03-21-2013, 12:04 AM
jim829
Re: Converting Binary
I assume you are talking about converting from a binary string to a decimal value. Well, you could use the following from the JDK.

Code:

```String bitString = "10101"; int val = Integer.parseInt(bitString, 2);```
Or do it yourself.
Lets assume this was decimal.

int n = 0;
String nStr = "1234";
1. Remove the left most digit and add its representative value into n
2. if no digits left, you are done
3. Multiply n by 10
4. go to 1.

Regards,
Jim