Java – (Java) Specify number of bits (length) when converting binary number to string

binaryjava

I'm trying to store a number as a binary string in an array but I need to specify how many bits to store it as.

For example, if I need to store 0 with two bits I need a string "00". Or 1010 with 6 bits so "001010".

Can anyone help?

EDIT: Thanks guys, as I'm rubbish at maths/programming in general I've gone with the simplest solution which was David's. Something like:

binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
                        binaryString.insert(0, "0");
}

It seems to work fine, so unless it's very inefficient I'll go with it.

Best Answer

Use Integer.toBinaryString() then check the string length and prepend it with as many zeros as you need to make your desired length.