我在将十进制转换为二进制时遇到问题。如何使用字符串生成器从一开始就添加 0 来转换二进制文件?
while (num != 0){
int digit = num % 2;
buf.append(digit);
num = num/2;
}
System.out.println(num);
试试这个(对您的原始代码进行最少的修改)......
int num=8;
StringBuilder buf = new StringBuilder();
while (num != 0){
int digit = num % 2;
buf.append(digit);
num = num/2;
}
System.out.println(buf.reverse());
十进制数可以通过将数字除以 2 并记下余数来转换为二进制 例如,如果您将 12 作为十进制数,则二进制数将为 1100
手动输出:
2 12
2 6 0
2 3 0
2 1 1
1
将十进制转换为二进制的代码是
class Binary
{
public StringBuffer calBinary(int decnum){
StringBuffer sBuf = new StringBuffer();
int temp=0;
while(decnum>0){
temp = decnum%2;
sBuf.append(temp);
decnum = decnum / 2;
}
return sBuf.reverse();
} }
public class Sri {
public static void main(String[] args) throws IOException {
System.out.println(" please enter the decimal number to convert into binary");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine());
Binary K = new Binary();
StringBuffer result = K.calBinary(decnum);
System.out.println(result);
}
}
尝试使用字符串生成器类中的 reverse() 方法。类似于以下内容:
buf = buf.reverse();
你可以试试这个
int num=10;
StringBuilder buf1=new StringBuilder();
StringBuilder buf2=new StringBuilder();
while (num != 0){
int digit = num % 2;
buf1.append(digit); // apend 0101 order
num = num/2;
}
String binary=buf1.reverse().toString();// reverse to get binary 1010
int length=binary.length();
if(length<8){
while (8-length>0){
buf2.append("0");// add zero until length =8
length++;
}
}
String bin=buf2.toString()+binary;// binary string with leading 0's
System.out.println(bin);
现场演示在这里。
输出
00001010
您可以对数组执行相同的操作,如下所示
int num=10;
int[] binArr=new int[8];
int j=0;
while (num != 0){
int digit = num % 2;
binArr[binArr.length-1-j]=digit;
num = num/2;
j++;
}
System.out.println(Arrays.toString(binArr).replaceAll("\\,|\\[|\\]",""));
如果只允许追加,则可能应该使用递归:
String toBinaryString(int num)
{
StringBuilder sb = new StringBuilder();
if (num > 1)
{
sb.append(decimalToBinary(num/2)); // or num >> 1
}
sb.append((num & 1));
return sb.toString();
}
不是世界上最有效的代码,但您确实指定了两者StringBuilder
并仅附加。负数的处理留给读者作为练习。