10进制转化位2进制,16进制

把十进制整数转化为二进制:
1.除基倒取余数法,让十进制不断被2整除,直到商为0,把余数从下到上组合;

public   static void function(int n){
      int t=0;//用来记录位数
      int m=0;//用来记录最后的二进数
      int r=0;//用来存储余数
      while( n!=0){
      r=n%2;
      n=n/2;
      m+=r* Math().pow(10,t);
      t++;
  }
     System.out.println(m);
      }
public class JavaApplication29 {
    public static void main(String[] args) {
    
      int s=12;
      int[] array=new int[100];
      int i=0;
      while(s!=0){
        int  r=s%2;
        array[i]=r;
        s=s/2;
        i++;
      }
      for(int j=i;j>=0;j--){
     System.out.println(array[j]);
    }
    }  
}

Int 在java中的存储范围是32位,则可以使用
字符串拼接

public   static void function(int n){
      String str=" ";
      while(n !=0){
          str=n%2+str;
          n=n/2;
      }
  
     System.out.println(str);
      } 
  }   

2.利用移位操作实现:把最高为位数移至最低位(移31位),除过最低位其余位置清零,使用&操作,可以和1&,然后把这个数按十进制输出;在移次高位,做相同的操作,直至最后一位

public class JavaApplication29 {
   public static void main(String[] args) {
        int n=12;
       binary(n);
    }
 public   static void binary(int n){
      
      for(int i=31;i>=0;i--){
         
       System.out.println(n>>>i&1);
      }
      
  }   
}

3.调用API函数

public class JavaApplication29 {
    public static void main(String[] args) {
        int n=12;
      function(n);
    }
  public   static void function(int n){
      
     String result=Integer.toBinaryString(n);
     //int r=Integer.parseInt(result);
     //System.ot.println(r);
       System.out.println(result);
      }
      
  }   

把十进制整数转化为十六进制:
1.除16取余,逆序排列

public class Java {
    public static void main(String[] args) {
      int s=16;
      char[] array=new char[100];
      int i=0;
      while(s!=0){
         int  r=s%16;
          if(r>9){
              array[i]=(char)(r-10+'A'); 
              i++;
          } else{
              array[i]=(char)(r+'0');
              i++;
          }
          s=s/16;
      }
      for(int j=i;j>=0;j--){
       System.out.print(array[j]) ;
      }
    
    }
}

2.格式化输出

public class Java {
    public static void main(String[]  args) {
        int n=12;
     System.out.printf("%x\n",n);
    }
3.ApI
public class Java {
    public static void main(String[]  args) {
      int s=12;
     System.out.println(Integer.toHexString(s).toUpperCase( ));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值