10位以内二进制数字转十进制计算器(Printing the Decimal Equivalent of a Binary Number)

挺有成就感的一个小程序,二进制转十进制。

代码如下:

//JHTP Exercise 4.31: Printing the Decimal Equivalent of a Binary Number
//by pandenghuang@163.com
/*(Printing the Decimal Equivalent of a Binary Number) Write an application that inputs an
*integer containing only 0s and 1s (i.e., a binary integer) and prints its decimal equivalent. [Hint: Use
*the remainder and division operators to pick off the binary number’s digits one at a time, from right
*to left. In the decimal number system, the rightmost digit has a positional value of 1 and the next
*digit to the left a positional value of 10, then 100, then 1000, and so on. The decimal number 234
*can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, the rightmost digit has
*a positional value of 1, the next digit to the left a positional value of 2, then 4, then 8, and so on.
*The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or 1 + 0 + 4 + 8 or, 13.]*/

import java.util.Scanner;
import java.math.*;

public class Binary2Decimal {

	public static void main(String[] args) {
		int binary=0;
		int decimal=0;
		int len=0;
		int[] binaryDigit=new int[10];
		int counter=0;
		int tempBinary=0;
		
		Scanner input=new Scanner(System.in);
		System.out.print("请输入要转换的二进制数字:");
		binary=input.nextInt();
		tempBinary=binary;
		//1011
		len=String.valueOf(tempBinary).length();
		while (counter<len){
			binaryDigit[counter]=(int)(tempBinary%10);
			tempBinary/=10;
			counter++;
			}
		counter=0;
		//decimal=1*1+1*2+0*2*2+1*2*2*2=11
		while (counter<len)
		{
			decimal+=binaryDigit[counter]*(int)Math.pow(2, counter);
			counter++;
		}
		System.out.printf("二进制数%d对应的十进制数为: %d",binary,decimal);
		}
}

运行结果:

请输入要转换的二进制数字:1100001110
二进制数1100001110对应的十进制数为: 782

请输入要转换的二进制数字:10011110
二进制数10011110对应的十进制数为: 158



    原文作者:进制转换
    原文地址: https://blog.csdn.net/hpdlzu80100/article/details/51702188
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞