java二进制转化为十进制_用Java将二进制转换为十进制的程序

java二进制转化为十进制

Here you will get program to convert binary to decimal in Java.

在这里,您将获得在Java中将二进制转换为十进制的程序。

There are mainly two ways to convert a binary number to decimal number in Java.

在Java中,主要有两种将二进制数转换为十进制数的方法。

1. By using parseInt() method of Integer class. 2. By using user defined logic.

1.通过使用Integer类的parseInt()方法。 2.通过使用用户定义的逻辑。

用Java将二进制转换为十进制的程序 (Program to Convert Binary to Decimal in Java)

By using Integer.parseInt()

通过使用Integer.parseInt()

Integer.parseInt() method takes two arguments. First argument is a string and second argument is the base or radix in which we have to convert the number. The output is the integer represented by the string argument in the specified radix. Below is the program for it.

Integer.parseInt()方法采用两个参数。 第一个参数是一个字符串,第二个参数是我们必须在其中转换数字的基数或基数。 输出是由指定基数中的字符串参数表示的整数。 下面是它的程序。

import java.util.Scanner;
 
class BinaryToDecimal
{
        public static void main(String args[])
        {
            Scanner s=new Scanner(System.in);
            
            System.out.println("Enter a binary number:");
 
            String n=s.nextLine();
            
            System.out.println(Integer.parseInt(n,2));
        }
}

Without using Integer.parseInt()

不使用Integer.parseInt()

In this method we have to define our own logic for converting binary number to decimal. The approach that we will use here is mentioned in below example.

在这种方法中,我们必须定义自己的逻辑,以将二进制数转换为十进制。 下面的示例中提到了我们将在此处使用的方法。

binary to decimal example

Image Source

图片来源

The program that implements above approach is mentioned below.

下面介绍实现上述方法的程序。

import java.util.Scanner;
 
class BinaryToDecimal
{
        public static void main(String args[])
        {
            Scanner s=new Scanner(System.in);
            
            System.out.println("Enter a binary number:");
            int n=s.nextInt();
            
            int decimal=0,p=0;
            
            while(n!=0)
            {
                decimal+=((n%10)*Math.pow(2,p));
                n=n/10;
                p++;
            }
            
            System.out.println(decimal);
        }
}

Output

输出量

Program to Convert Binary to Decimal in Java

If you found anything missing or incorrect in above programs then please mention it by commenting below.

如果您在上述程序中发现任何丢失或不正确的内容,请在下面的评论中提及。

翻译自: https://www.thecrazyprogrammer.com/2015/11/program-to-convert-binary-to-decimal-in-java.html

java二进制转化为十进制

  • 15
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值