package test;
/**
* 进制转换
* @author
*
*/
public class Test {
private static final int NUM_TWO = 2;
private static final int NUM_EIGHT = 8;
private static final int NUM_HEX = 16;
private static final char[] HEX = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e'};
/**
* 得到二进制
* @param num
* @return
*/
public static String getTwo(int num){
StringBuffer sb = new StringBuffer();
int remainder ;//= num % NUM_TWO;//余数
int quotient ;//= num / NUM_TWO;//商
do{
remainder = num % NUM_TWO;
quotient = num / NUM_TWO;
num = quotient;
sb.insert(0, remainder);
}while(quotient != 0);
return sb.toString();
//return Integer.toBinaryString(num);
}
/**
* 得到八进制
* @param num
* @return
*/
public static String getEight(int num){
StringBuffer sb = new StringBuffer();
int remainder ;//= num % NUM_EIGHT;//余数
int quotient ;//= num / NUM_EIGHT;//商
do{
remainder = num % NUM_EIGHT;
quotient = num / NUM_EIGHT;
num = quotient;
sb.insert(0, remainder);
}while(quotient != 0);
return sb.toString();
//return Integer.toOctalString(num);
}
/**
* 得到十六进制
* @param num
* @return
*/
public static String getHex(int num){
StringBuffer sb = new StringBuffer();
int remainder ;//= num % NUM_HEX;//余数
int quotient ;//= num / NUM_HEX;//商
do{
remainder = num % NUM_HEX;
quotient = num / NUM_HEX;
num = quotient;
sb.insert(0, HEX[remainder]);
}while(quotient != 0);
return sb.toString();
// return Integer.toHexString(num);
}
public static void main(String[] args) {
int num = 11;
System.out.println("十进制数:"+num);
System.out.println("二进制为:"+getTwo(num));
System.out.println("八进制为:"+getEight(num));
System.out.println("十六进制为:"+getHex(num));
}
}
每个函数中被注释的return为库函数可以直接调用就可以得到结果。
十进制转换为2、8、16进制
最新推荐文章于 2021-12-02 23:34:33 发布