進位制間的轉換
阿新 • • 發佈:2020-12-14
十六進位制轉十進位制
方法一:
/*
*問題描述
從鍵盤輸入一個不超過8位的正的十六進位制數字符串,將它轉換為正的十進位制數後輸出。
注:十六進位制數中的10~15分別用英文字母A、B、C、D、E、F或者a,b,c,d,e,f表示。
*樣例輸入
FFFF
*樣例輸出
65535
*/
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
System.out.print("輸入十六進位制數:");
Scanner sc = new Scanner(System.in);
String str = sc.next();
char[] a = str.toCharArray();
int[] b = new int[a.length];
int sum = 0;
for (int i = 0; i < a.length; i++) {
if ((a[i] >= 'a') && (a[i] <= 'z')) {
b[i] = a[i] - 'a' + 10 ;
} else if ((a[i] >= 'A') && (a[i] <= 'Z')) {
b[i] = a[i] - 'A' + 10;
} else
b[i] = a[i] - '0';
}
for (int i = 0; i < b.length; i++) {
sum+= b[b.length - i - 1] * (int) (Math.pow(16, i));
}
System. out.println("" + sum);
}
}
輸出結果:
輸入十六進位制數:ffff
轉成十進位制為:65535
方法二:
利用Java對String物件的強制轉換函式
詳情可查閱Java的API---------->java線上API
1、對字串引數的解析就是按照這個進位制標準進行轉化成10進位制的數值。
比如 :
System.out.println(Integer.parseInt("ffff", 16));
System.out.println(Integer.parseInt("123",10));
輸出為:
65535
123
十進位制轉十六進位制
/*
* 先輸入一個整型數字tr,判斷其是否為0,若為0,則其16進位制同樣為0;
* 若n不為0,則對16取餘,並轉換成16進位制相應的字元;
* n=n/16,重複過程2、3,用字元陣列s依次儲存每一位;
* 輸出的時候逆序輸出即可
*/
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
System.out.print("請輸入十進位制數:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("轉成十六進位制為:" + intTo(n));
}
public static String intTo(int n) {
StringBuffer str = new StringBuffer();
char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
while (n != 0) {
str = str.append(b[n % 16]);
n = n / 16;
}
String str1 = str.reverse().toString();
return str1;
}
}
輸出結果:
請輸入十進位制數:65535
轉成十六進位制為:FFFF
函式說明:
十進位制轉二進位制
/*利用字串的並置
int型別資料加上字串型別資料自動轉換為字串*/
import java.util.Scanner;
public class Demo3 {
public static void main(String[] args) {
System.out.print("輸入十進位制數:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str = "";
while (n != 0) {
str = n % 2 + str;
n = n / 2;
}
System.out.println("轉換為二進位制數:" + str);
}
}
輸出結果:
輸入十進位制數:10
轉換為二進位制數:1010
二進位制轉十進位制
/* 原理和十六進位制轉十進位制是一樣的*/
import java.util.Scanner;
public class Demo4 {
public static void main(String[] args) {
System.out.print("輸入二進位制數:");
Scanner sc = new Scanner(System.in);
String str = sc.next();
char a[] = str.toCharArray();
int b[] = new int[a.length];
int sum = 0;
for (int i = 0; i < a.length; i++) {
if ((a[i] >= '0') && (a[i] <= '1')) {
b[i] = a[i] - '0';
} else {
System.out.println("不是二進位制數!");
}
}
for (int i = 0; i < a.length; i++) {
sum += b[a.length - 1 - i] * (int) Math.pow(2, i);
}
System.out.println("轉換為十進位制為:" + sum);
}
}
輸出結果:
輸入二進位制數:1010
轉換為十進位制為:10