您的位置:首页 > 编程语言 > Java开发

十六进制转换的高效算法

2017-11-21 11:16 127 查看
import java.util.Scanner;
public class Text {
public static void main(String[] args) {
System.out.print("Input a decimal number : ");
Scanner input=new Scanner(System.in);
int decimalNum=input.nextInt();
System.out.println("Hex number is "+decimalToHex(decimalNum)+"H");
System.out.print("Input a hex number : ");
String hexNum=input.next();
System.out.println("Decimal number is "+hexToDecimal(hexNum.toUpperCase()));//toUpperCase()使输入的字母可以不区分大小写
}

public static String decimalToHex(int decimal) {
String hex="";
while(decimal!=0) {
int value=decimal%16;
hex=toHexChar(value)+hex;//不能简单的hex+=toHexChar(value);因为输出的字符串有顺序
decimal/=16;
}
return hex;
}
public static char toHexChar(int hexValue) {
if(hexValue>=10&&hexValue<=15)
return (char)(hexValue-10+'A');
else
return (char)(hexValue+'0');
}

public static int hexToDecimal(String hex) {
int decimal=0;
for(int i=0;i<hex.length();i++) {
char hexChar=hex.charAt(i);
decimal=decimal*16+hexCharToDecimal(hexChar);//高效算法
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if(ch>='A'&&ch<='F')
return ch-'A'+10;
else
return ch-'0';
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java