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.