Generating an array of binary numbers

Hi, guys

I want to create a method that would return an array of binary numbers for a given size.

Say, for example I want to know all possible possible binary numbers of 4 digits, that method should return numbers (or strings) from 0000, 0001 ... to 1111.

I really cant think of anything, right now, maybe there is a method in java or something. Or maybe somebody can give me a hint.

Thanks,

Val.

[440 byte] By [valyuha] at [2007-9-26 1:31:25]
# 1
Hint... java.lang.Integer.toBinaryString()
neville_sequeira at 2007-6-29 1:30:57 > top of Java-index,Archived Forums,Java Programming...
# 2

FYI: in general, numbers are in the binary number system in digital computers. So "generating an array of binary numbers" doesn't really make any sense... Here's some code that doesn't work correctly:String[] getBinaryNumbers(int length) {

int max = (int)(Math.pow(2,length) + .1);

String[] s = new String[max];

for (int a = 0; a < max; a++)

s[a] = Integer.toBinaryString(a);

return s;

}

It doesn't work correctly because it doesn't pad the numbers with 0's to produce eg. "0010".

jsalonen at 2007-6-29 1:30:57 > top of Java-index,Archived Forums,Java Programming...
# 3

public String[] getBinStrings( int numDigits) {

int numElements = (int)java.lang.Math.pow(2,numDigits);

String[] binaryStrings = new String[numElements];

for( int j = 0; j < numElements; j++ ) {

binaryStrings[j] = Integer.toBinaryString(j);

}

return binaryStrings;

}

parthasarkar at 2007-6-29 1:30:57 > top of Java-index,Archived Forums,Java Programming...
# 4
thanks guys,I forgot about the Integer.toBinaryString() methodNow everything works great,Val.
valyuha at 2007-6-29 1:30:57 > top of Java-index,Archived Forums,Java Programming...