public class TowAdecimal{
private int sum;//用于转换值
private static String s = "11";//十六进制的值
public static void main(String[] args){
TowAdecimal a = new TowAdecimal();
a.char_value(s);
}
//------------------------------------------------------------
public void char_value(String s){
if (s == null) {//判断.传进来的是不是null 如果是null 就没必要往下运算,就直接终止函数运行
System.out.println( "请输入一个十六进制的字符串,null不是字符串" );
return;
}
for(int i=0; i < s.length(); ++i){
char c = s.charAt(s.length()-1-i);//从右往左获得字符串
if (int_value(c,i)) {//这个是根据输入的字符,如果有一位不正确,就终止此函数运行,就不输出错误的结果了
return;
}
}
if (sum == 0) {
System.out.println( 0 );
}else{
sum_2(sum);
}
}
//------------------------------------用于把字符串解析成整型值----------------
public boolean int_value(char c,int N_Ci_Fang ){//这个方法是把字符转为整形值
int i = 0;
if (c == 'a') {
i = 10;
}else if (c == 'b') {
i = 11;
}else if (c == 'c') {
i = 12;
}else if (c == 'd') {
i = 13;
}else if (c == 'e') {
i = 14;
}else if (c == 'f') {
i = 15;
}else if (c == '0') {
i = 0;
}else if (c == '1') {
i = 1;
}else if (c == '2') {
i = 2;
}else if (c == '3') {
i = 3;
}else if (c == '4') {
i = 4;
}else if (c == '5') {
i = 5;
}else if (c == '6') {
i = 6;
}else if (c == '7') {
i = 7;
}else if (c == '8') {
i = 8;
}else if (c == '9') {
i = 9;
}else{
System.out.println( "十六进制每位上的值最大为 f , 请输入 0~f 之间的值" );
return true;
}
sum_value(i,N_Ci_Fang);
return false;
}
//-------;----------------------------用于把整型值计算,得出十进制----------------
public void sum_value( int value,int N_Ci_Fang){
// System.out.println( Math.pow(16,0)); //是16的0次方 里面的两个参数都是double类型
this.sum += value*(int)Math.pow(16,N_Ci_Fang);
}
//----------------------------------计算二进制的值---------------------
public void sum_2(int sum){
int sum2= sum;//用于承载每次除2的那个值
StringBuffer s = new StringBuffer();
for(int i=1; i<999999999; ++i){
if (sum2 == 1) {
s.append(1);
break;
}
s.append(sum2%2);
sum2 = sum2/2;
}
String_Buffer(s);
}
//----------------------StringBuffer--------------------------------------
public void String_Buffer( StringBuffer s){
StringBuffer value = new StringBuffer();
for(int i=0; i < s.length(); ++i){
value.append(s.charAt(s.length()-1-i));
}
System.out.println( value );
}
//------------------------------------------------------------
//------------------------------------------------------------
}