How to get 0-padded binary representation of an integer in java?

khachik picture khachik · Dec 12, 2010 · Viewed 134.9k times · Source

for example, for 1, 2, 128, 256 the output can be (16 digits):

0000000000000001
0000000000000010
0000000010000000
0000000100000000

I tried

String.format("%16s", Integer.toBinaryString(1));

it puts spaces for left-padding:

`               1'

How to put 0s for padding. I couldn't find it in Formatter. Is there another way to do it?

P.S. this post describes how to format integers with left 0-padding, but it is not for the binary representation.

Answer

Samuel Parsonage picture Samuel Parsonage · Dec 12, 2010

I think this is a suboptimal solution, but you could do

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')