例如:輸入123F5,輸出:0001 0011 1111 0101。
import java.util.Scanner; public class C1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); Scanner scn = new Scanner(System.in); //提示使用者輸入16進位數字 System.out.print("請輸入數字:"); String userenter = scn.next(); userenter = userenter.toUpperCase(); //先將使用者輸入的文字全部轉大寫 int a = userenter.length(); char[] newuserenter = new char[a]; for(int i = 0 ; i < newuserenter.length ; i++) //將使用者輸入的字串轉成字元 { newuserenter[i] = userenter.charAt(i); } for(int i = 0 ; i < newuserenter.length ; i++) //判斷每個字元的對應二進位數字並印出結果 { switch(newuserenter[i]) { case '0' : System.out.print("0000 "); break; case '1' : System.out.print("0001 "); break; case '2' : System.out.print("0010 "); break; case '3' : System.out.print("0011 "); break; case '4' : System.out.print("0100 "); break; case '5' : System.out.print("0101 "); break; case '6' : System.out.print("0110 "); break; case '7' : System.out.print("0111 "); break; case '8' : System.out.print("1000 "); break; case '9' : System.out.print("1001 "); break; case 'A'/*10*/ : System.out.print("1010 "); break; case 'B'/*11*/ : System.out.print("1011 "); break; case 'C'/*12*/ : System.out.print("1010 "); break; case 'D'/*13*/ : System.out.print("1011 "); break; case 'E'/*14*/ : System.out.print("1110 "); break; case 'F'/*15*/ : System.out.print("1111 "); break; } } } }
沒有留言:
張貼留言