JAVA进制转换汇总

JAVA进制转换

一、十进制转化为十六进制

方法一:

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sca=new Scanner(System.in);
		int in=sca.nextInt();
		String str= Integer.toHexString(in).toUpperCase();
		System.out.println(str);

	}
} 

方法二:

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sca=new Scanner(System.in);
		int in=sca.nextInt();
		StringBuffer s=new StringBuffer();
		while(in>0){
			int t=in%16;
			switch (t) {
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
				s.append(t+"");break;
			case 10:
				s.append('A');break;
			case 11:
				s.append('B');break;
			case 12:
				s.append('C');break;
			case 13:
				s.append('D');break;
			case 14:
				s.append('E');break;
			case 15:
				s.append('F');break;
			}
			in=in/16;
		}
		System.out.println(s.reverse());
	}
} 

二、十六进制转化为十进制

注意:十六进制中的数10~15均用大写字母A、B、C、D、E、F表示。

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);
		String str = sca.nextLine();
		char ch[] = str.toCharArray();
		long sum = 0;
		int l=ch.length;
		for (int i = 0; i < l; i++) {
			if (ch[i] >= 'A') {
				sum = (long) (sum + Math.pow(16,l-i-1 ) * (ch[i] - 'A' + 10));
			} else {
				sum = (long) (sum + Math.pow(16, l-i-1) * Integer.parseInt(ch[i]+""));
			} 
		}
		System.out.println(sum);

	}
} 

你可能感兴趣的:(JAVA,Java学习)