十进制->二进制、八进制、十六进制:除进制数取余倒序法
二进制、八进制、十六进制->十进制:按位乘进制数上幂法
1.十进制<->二进制
import java.util.LinkedList;
public class DecimalAndBinary {
/**
* @param num
* 十进制->二进制
*/
public static String Decimal2Binary(int num){
LinkedList<Integer> list = new LinkedList<Integer>();
int temp = 0;
while(num != 0){
temp = num % 2;
list.add(temp);
num = num / 2;
}
StringBuilder sb = new StringBuilder();
for (int i = list.size() - 1; i >= 0; i--) {
sb.append(list.get(i));
}
return sb.toString();
}
/**
* @param str
* 二进制->十进制
*/
public static int Binary2Decimal(String str){
Integer num = 0;
char[] cha = str.toCharArray();
int length = str.length();
for (int i = 0; i < cha.length; i++) {
num = num + Integer.valueOf(String.valueOf(cha[i]))*(int)Math.pow(2, Double.valueOf(length) - 1);
length--;
}
return Integer.valueOf(String.valueOf(num));
}
}
2.十进制<->八进制
import java.util.LinkedList;
public class DecimalAndOctal {
/**
* @param num
* 十进制->八进制
*/
public static String Decimal2Octal(int num){
java.util.List<Integer> list = new LinkedList<Integer>();
int temp = 0;
while(num != 0){
temp = num % 8;
list.add(temp);
num = num / 8;
}
StringBuffer sb = new StringBuffer();
for (int i = list.size() - 1; i >= 0; i--) {
sb.append(list.get(i));
}
return sb.toString();
}
/**
* @param input
* 八进制->十进制
*/
public static int Octal2Decimal(String input){
char[] cha = input.toCharArray();
int length = input.length();
int num = 0;
for (int i = 0; i < cha.length; i++) {
num = num + Integer.valueOf(String.valueOf(cha[i]))*(int)Math.pow(8, Integer.valueOf(length - 1));
length--;
}
return num;
}
}
3.十进制<->十六进制
import java.util.ArrayList;
import java.util.List;
public class DecimalAndHex {
public static String get16Char(int temp){
String s = null;
switch (temp) {
case 10:
s = "A";
break;
case 11:
s = "B";
break;
case 12:
s = "C";
break;
case 13:
s = "D";
break;
case 14:
s = "E";
break;
case 15:
s = "F";
break;
default:
break;
}
return s;
}
/**
* @param num
* 十进制->十六进制
*/
public static String Decimal2Hex(int num){
List<String> list = new ArrayList<String>();
int temp = 0;
while(num != 0){
temp = num % 16;
if (temp >= 10) {
list.add(get16Char(temp));
}else {
list.add(String.valueOf(temp));
}
num = num / 16;
}
StringBuffer sb = new StringBuffer();
for (int i = list.size() - 1; i >= 0; i--) {
sb.append(list.get(i));
}
return sb.toString();
}
public static Integer get16Num(char character){
Integer num = null;
switch (character) {
case 'A':
num = 10;
break;
case 'B':
num = 11;
break;
case 'C':
num = 12;
break;
case 'D':
num = 13;
break;
case 'E':
num = 14;
break;
case 'F':
num = 15;
break;
default:
break;
}
return num;
}
/**
* @param input
* 十六进制->十进制
*/
public static int Hex2Decimal(String input){
char[] cha = input.toCharArray();
int num = 0;
for (int i = 0; i < cha.length; i++) {
if (get16Num(cha[i]) != null) {
num = num + get16Num(cha[i])*(int)Math.pow(16, cha.length - 1 - i);
}else {
num = num + Integer.valueOf(String.valueOf(cha[i]))*(int)Math.pow(16, cha.length - 1 - i);
}
}
return num;
}
}