conversion decimal to 2^12 binary form
anyone can help me how to convert a decimal number into 2^12 binary form...here the code that i used for conversion. bt it's not 2^12 binary for. pls do anyone help me to solve this prob.
import java.io.*;
import java.lang.*;
public class convert {
public static void main(String[] args) throws IOException{
BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any number:");
String sn = bf.readLine();
int i = Integer.parseInt(sn);
String s = Integer.toBinaryString(i);
System开发者_运维知识库.out.println("Binary number is:" + s);
}
}
I'm going to assume that the OP wants a binary string padded to 12 digits. There are many ways to do this, here is one:
String s = Integer.toBinaryString(i);
StringBuilder buf = new StringBuilder();
for (int j = 1; j <= 12 - s.length(); j++) {
buf.append('0');
}
buf.append(s);
s = buf.toString();
System.out.println(s);
It may be shorter with formatter. Something like,
String s = Integer.toBinaryString(i);
System.out.println(String.format("%012d", Integer.valueOf(s)));
精彩评论