# Array type

• September 15th, 2010, 04:28 AM
arpit2309
Array type
Hello !!!
i want to store some binary numbers in an array::
suppose i have five binary numbers ::
001,0010,0011,00,0000011;
so which type of array should i select?
also how to initialize that array!!
so that i can retrieve it as binary numbers not the ascii values of 0s and 1s(as in String type).

• September 15th, 2010, 08:26 AM
ProgramThis
Re: Array type
What have you done to try and help yourself? Have you even tried reading any of the Java docs or Googling? Try doing a little research before asking for the answer, it isn't hard to find.
• September 15th, 2010, 09:30 AM
Norm
Re: Array type
Everything in a computer is in binary. For example byte, short, int, long are all stored as binary (8 binary bits to a byte).

What do you want to be stored when you say "binary"?
• September 15th, 2010, 10:58 AM
nuzzle
Re: Array type
Quote:

Originally Posted by arpit2309
Hello

The only way you can preserve leading zeroes in numbers is to actually store the numbers as Strings. So I suggest you make it a String array.

Then when you need to convert from a binary String representation to a decimal number you can use the parseInt method of the Integer class.
Code:

```String s="0011"; int n=0; try {   n = Integer.parseInt(s, 2); } catch (NumberFormatException e) {   // conversion error - do something }```
A complication here is that parseInt can throw an exception so the call must be made within a try-catch block.

The 2 in the parseInt call (the radix) means the String should be interpreted as a binary number.

If you print n after the conversion it should be 3. This is because 11 in binary is 3 in decimal. Note however that if you were to extract the internal binary representation of n you would find it to be 11 as expected.

If you change the radix to 10, n will be 11. This is because 11 in decimal is 11 in decimal (seems reasonable). The internal binary representation of n however will be 1011.

If you don't have to preserve leading zeroes of the binary Strings you can convert them to ints and store them in an int array. But how do you get the binary String representation back? Amazingly the Integer class offers a method also for that called toBinaryString.