Add leading zeros for binary conversion in java

If u convert Decimal 15 to binary,you will get  Binary 1110 So you may want to add leading zero Ex:00001110

Step1:Find how many zeros do you need ?

if your input is16 then log2 16=4 zeros
if your input is 15 then log2 15=3 zeros not correct :-) So check 3 mod 2  !=0 and add one to it 3+1=4



int zeros=0;        
zeros=(int) (Math.log(input)/ Math.log(2));
if (zeros%2!=0) zeros=zeros+1;


Step2:Add these zeros to your binary output


String formatted=String.format("%0"+zeros+"d\n", Integer.parseInt(Integer.toBinaryString(count)));
System.out.println(formatted);








No comments:

^ Top