Alex Rivera | Logout

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

Asked 2010-12-12T11:30:59.350
154

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.

Edit
Report

1 Answer

17

You can use Apache Commons StringUtils. It offers methods for padding strings:

StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');
answered 2013-05-08T08:04:54.867

Your Answer