小弟正在学习J2SE的编程,遇到该问题,于是写出了这样的代码:
package ch2;public class Class2 {
public static void main(String[] args){
int a = 100;//假定转换的数字为100
b(a);
System.out.print("\n");
o(a);
}
public static void b(int n){
int temp = n;
System.out.print("二进制表示结果:");
while(temp!=0){
System.out.print(temp%2);
temp/=2;
};
return;
}
public static void o(int n){
int temp = n;
System.out.print("八进制表示结果:");
while (temp!=0){
System.out.print(temp%8);
temp/=8;
};
return;
}//由于技术不行,结果我十六进制输出实在不知道怎么写出来了,就写了个八进制和二进制
}
但是发现结果不正确:
二进制表示结果:0010011
八进制表示结果:441求大神帮忙修改下。

解决方案 »

  1.   

    Integer类里面封装了这个方法
    package jiakai;public class MyTest {
    public static void main(String[] args) {
    int a = 256;
    System.out.println(Integer.toBinaryString(a));
    System.out.println(Integer.toOctalString(a));
    System.out.println(Integer.toHexString(a));
    }}
      

  2.   


    我懂你的意思,我也知道JAVA肯定封装了这类算法,可是,我现在是要写一段关于这个算法的程序,呵呵
      

  3.   

    进制转换是取余之后倒序输出。你不是倒序输出的。再者16进制你可以弄数组对照char[] str = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};余就是 str[] 几。还有,如果你想让你的程序健壮的话。你还应该有个小的注意。 如果是负数怎么办。负数你是否想转换成补码形式转换。那就还需要写一个负数补码的方法。只提供思路。帮你写代码是害你。
      

  4.   

    算法有问题,用辗转相除法
    就是为了得到以2为因子的权值http://baike.baidu.com/view/1426817.htm
    100
    2*50
    2*2*25
    2*2*(2*12 + 1)
    2*2*(2*(2*6) + 1)
    2*2*(2*(2*(2*3)) + 1)
    2*2*(2*(2*(2*(2*1+1))) + 1)权重最大的是2^6
    紧接着是2^5
    还有一个2^2
    其它权值都是0
    1100100