[ java ] 一個IP地址是用四個字節(每個字節8個位)的二進制碼組成。請將32位二進制碼錶示 的IP地址轉換爲十進制格式表示的IP地址輸出。

import java.util.Scanner;
public class Review {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		String a = input.nextLine();
		int[] b = new int[4];
		int[] c = new int[4];
		for(int i =0;i<4;i++) 
		{
			c[i] = Integer.parseInt(a.substring((i+1)*8-8, (i+1)*8)); //32位分成8位
		}
		
		for(int i =0;i<4;i++)
		{
			for(int j = 0;j<8;j++)
			{
				b[i]+=Math.pow(2, j)*(c[i]%10);// 二進制轉換成十進制
				c[i] /= 10;
			}
			if(i!=3)
				System.out.print(b[i]+".");
			else System.out.print(b[i]);
		}
		input.close();
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章