进制转换

package com.byd.core;


import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Stack;

public class NumberUtils {
	/**
	 * 将指点的数字对象按照指点的规则格式化, 例如:###.00,
	 * @param format String 格式
	 * @param obj Double 需转换的Double类型数据
	 * @return 格式化后的字符串
	 */
	public static String format(String format, double obj) {
		DecimalFormat formater = new DecimalFormat(format);
		return formater.format(obj);
	}
	
	/**
	 * 将指点的数字对象按照指点的规则格式化, 例如:###.00,
	 * @param format String
	 * @param obj Float 需转换的Float类型数据
	 * @return 格式化后的字符串
	 */
	public static String format(String format, float obj) {
		DecimalFormat formater = new DecimalFormat(format);
		return formater.format(obj);
	}

	/**
	 * 获取指定位数的随机数
	 * @param size int 位数
	 * @return 指定位数的随机数 long
	 */
	public static long getRandom(int size) {
		Double value = (Math.random() * Math.pow(10, size));
		return value.longValue();
	}
	
	/**
	 * 判断是否为整数
	 * @param value
	 * @return
	 */
	public static boolean isInteger(String value){
		try {
			Integer.valueOf(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	
	/**
	 * 判断是否为数字
	 * @param value
	 * @return
	 */
	public static boolean isNumeric(String value){
		try {
			Double.valueOf(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	
	public static Long createLong(String longValue){
		Long result;
		try {
			result = Long.parseLong(longValue);
		}
		catch (NumberFormatException e){
			return null;
		}
		return result;
	}
	
	public static Integer createInteger(String intValue){
		Integer result;
		try {
			result = Integer.parseInt(intValue);
		}
		catch (NumberFormatException e){
			return null;
		}
		return result;
	}
	
	public static Short createShort(String shortValue){
		Short result;
		try {
			result = Short.parseShort(shortValue);
		}
		catch (NumberFormatException e){
			return null;
		}
		return result;
	}
	
	public static String formatInteger(Integer integerValue, String defaultValue){
		if (integerValue == null){
			return defaultValue;
		}
		else{
			return String.valueOf(integerValue);
		}
	}
	
	public static String formatLong(Long longValue, String defaultValue){
		if (longValue == null){
			return defaultValue;
		}
		else{
			return String.valueOf(longValue);
		}
	}
	
	public static String formatShort(Short shortValue, String defaultValue){
		if (shortValue == null){
			return defaultValue;
		}
		else{
			return String.valueOf(shortValue);
		}
		
	}
	/**16进制转10进制**/
	public static Integer MD10(String value){
		if(value == null){
			return null;
		}else{
			return Integer.parseInt(value,16);
		}
	}
	/**10进制转16进制**/
	public static String MD16(Integer value){
		return Integer.toHexString(value).toString();
	}
	
	public static String baseNum(String num,int srcBase,int destBase){  
        if(srcBase == destBase){  
            return num;  
        }  
        String digths = "0123456789ABCDEF";  
        char[] chars = num.toCharArray();  
        int len = chars.length;  
        if(destBase != 10){//目标进制不是十进制 先转化为十进制  
            num = baseNum(num,srcBase,10);  
        }else{  
            int n = 0;  
            for(int i = len - 1; i >=0; i--){  
                n+=digths.indexOf(chars[i])*Math.pow(srcBase, len - i - 1);  
            }  
            return n + "";  
        }  
        return baseString(Integer.valueOf(num),destBase);  
    }  
		
	 public static String baseString(int num,int base){  
	        if(base > 16){  
	            throw new RuntimeException("进制数超出范围,base<=16");  
	        }  
	        StringBuffer str = new StringBuffer("");  
	        String digths = "0123456789ABCDEF";  
	        Stack s = new Stack();  
	        while(num != 0){  
	            s.push(digths.charAt(num%base));  
	            num/=base;  
	        }  
	        while(!s.isEmpty()){  
	            str.append(s.pop());  
	        }  
	        return str.toString();  
	    }  
	 

	  public static String NumberToTen(int beforeConversion, String number) {// 其它进制转成十进制
		      double result = 0;// 声明转换后的数值
		      String subString;
		      for (int i = 0; i < number.length(); i++) {// 根据字符串的长度循环获得单个元素
		         subString = number.substring(i, i + 1);// 将字符串按循环截取
		         if (beforeConversion == 16) {// 判断传入的是否是十六进制
		             subString = sixteenCharToNumber(subString);// 将字母转换成数字
		         }
		         result += Integer.parseInt(subString)* Math.pow(beforeConversion, number.length() - i - 1);// 返回转换的结果
		      }
		      //return (int) result;
		      DecimalFormat df = new DecimalFormat("0"); 
		      return df.format(result);
	  }
	  public static String TenToNumber(int afterConversion, String number) {// 十进制转成其他进制
		      int current = Integer.parseInt(number);// 将字符串转换成整数
		      String opResult = "";
		      if (afterConversion == 16) {// 判断转换后的数制是否是16进制
		         while (current >= afterConversion) {// 判断传入的数是否大于16,大于则逢16进一
		             opResult += sixteenNumberToChar(current % afterConversion);// 将数字转换成字母
		             current /= afterConversion;
		         }
		         if (current != 0)
		             opResult += sixteenNumberToChar(current);// 最终余数
		      } else {
		         while (current >= afterConversion) {// 判断传入的值是否大于转换后的数制
		             opResult += current % afterConversion;
		             current /= afterConversion;
		         }
		         if (current != 0)
		             opResult += current;// 最终余数
		      }
		      String riResult = "";// 倒序二进制字符串
		      for (int i = opResult.length() - 1; i >= 0; i--) {// 根据二进制的转换方式进行循环输出
		         riResult = riResult + opResult.substring(i, i + 1);
		      }
		      return riResult;
	  }
	  
	  public static String TenToNumber(String num){
		return Long.toHexString(Long.parseLong(num)).toUpperCase();

	  }

	  public static String sixteenCharToNumber(String s) {// 十六进制字母对应数字
	      	  String num = "";
		      if (s.equals("A") || s.equals("a"))
		         num = "10";
		      else if (s.equals("B") || s.equals("b"))
		         num = "11";
		      else if (s.equals("C") || s.equals("c"))
		         num = "12";
		      else if (s.equals("D") || s.equals("d"))
		         num = "13";
		      else if (s.equals("E") || s.equals("E"))
		         num = "14";
		      else if (s.equals("F") || s.equals("f"))
		         num = "15";
		      else
		         num = s;
		      return num;
	  }

	  public static String sixteenNumberToChar(int num) {// 十六进制数字对应字母
		      String c = "";
		      if (num == 10)
		         c = "A";
		      else if (num == 11)
		         c = "B";
		      else if (num == 12)
		         c = "C";
		      else if (num == 13)
		         c = "D";
		      else if (num == 14)
		         c = "E";
		      else if (num == 15)
		         c = "F";
		      else
		         c = String.valueOf(num);
		      return c;
	  }
	  
	  public static void main(String[] args) {// java程序的主入口处
		      String number;// 要转换的数
		      int beforeConversion, afterConversion;// 转换前的数制,转换后的数制
		      //Long temp1;
		      String result = "";// 经过数制转换后的结果
		      String temp="";
		      //String stop = "";
		      Scanner read = new Scanner(System.in);// 得到用户输入的值
		      //Date date=new Date();
		     // System.out.println(date.toLocaleString());
		      //do {
			         System.out.println("请输入三个参数(整数):待转换的数据   转换前的数制  转换后的数制");
			         number = read.next();
			         beforeConversion = read.nextInt();
			         afterConversion = read.nextInt();
			        // stop = "Q";
		     // } while (stop != "Q");// 跳出循环
		      try {
			         if (beforeConversion != 10) {// 判断转换前的数制是否是十进制
			             temp = String.valueOf(NumberToTen(beforeConversion,number));// 获得转换成十进制的数
			             //result = String.valueOf(TenToNumber(afterConversion, temp));// 十进制转换成其它进制
			             System.out.println(beforeConversion + "进制的数:" + number + ",转换成"
					                + afterConversion + "进制的数为:" + temp+"\n");
			             if(temp!=null){
					         Long t= Long.parseLong(temp);
					         for(int i=0;i<10;i++){
					        	t++;
					        	System.out.println(Long.toHexString(t).toUpperCase());
					         }
				         }
			         } else {
			             //result = String.valueOf(TenToNumber(afterConversion, number));// 十进制转换成其它进制
			        	 result = TenToNumber(number);
			        	 System.out.println("10进制数:"+number+",转换成16进制的数:"+result+"\n");
			        	 if(result!=null){
			        		 Long r = Long.parseLong(number);
			        		 for(int i=0;i<10;i++){
			        			 r++;
			        			 System.out.println(Long.toHexString(r).toUpperCase());
			        		 }
			        	 }
			         }      
			         //System.out.println(afterConversion + "进制的数:" + temp + ",转换成"
			           //     + beforeConversion + "进制的数为:" + Long.toHexString(Long.parseLong(temp)).toUpperCase());
		      }catch (Exception e) {
			         System.out.print("转换失败,请输入合法数据!");
			         System.exit(-1);// 所有程序(方法,类等)停止,系统停止运行
		      }
	  }
	
}

 

 

你可能感兴趣的:(Java,java)