【问题标题】:How to convert a binary String to a decimal string in Java如何在 Java 中将二进制字符串转换为十进制字符串
【发布时间】:2016-01-14 18:37:57
【问题描述】:

我正在做作业,以为我已经完成了,但老师告诉我这不是他想要的,所以我需要知道如何将存储为字符串的二进制数转换为十进制数字符串,不使用 Java 中的 length()、charAt()、power 函数和 floor/ceiling 之外的任何内置函数。

这就是我一开始的样子。

import java.util.Scanner;

public class inclass2Fall15Second {
    public static void convertBinaryToDecimalString() {
        Scanner myscnr = new Scanner(System.in);

        int decimal = 0;

        String binary;
        System.out.println("Please enter a binary number: ");
        binary = myscnr.nextLine();
        decimal = Integer.parseInt(binary, 2);
        System.out.println("The decimal number that corresponds to " + binary + " is " + decimal);
    }

    public static void main (String[] args) {
        convertBinaryToDecimalString();
    }
}

【问题讨论】:

  • 向我们展示您已经尝试过的内容。没有任何代码,我们无法为您提供帮助。
  • 您编码的语言是什么?如果没有这些信息,我们将无法为您提供帮助。
  • 我用这些信息更新了我的帖子。我很抱歉没有具体说明。
  • @BDM 检查我的更新解决方案

标签: java binary type-conversion decimal data-conversion


【解决方案1】:

要将基数 2(二进制)表示转换为基数 10(十进制),请将每个位的值乘以 2^(位位置)并将这些值相加。

例如1011 -> (1 * 2^0) + (1 * 2^1) + (0 * 2^2) + (1 * 2^3) = 1 + 2 + 0 + 8 = 11

由于二进制是从右到左读取的(即LSB(最低有效位)在最右边,MSB(最高有效位)在最左边),我们以相反的顺序遍历字符串。

要获取位值,请从字符中减去“0”。这将用 '0' 的 ascii 值减去字符的 ascii 值,得到该位的整数值。

要计算 2^(位位置),我们可以保留位位置的计数,并在每次迭代时递增计数。然后我们可以只做 1

这是实现上述内容的代码:

public static int convertBinStrToInt(String binStr) {
    int dec = 0, count = 0;
    for (int i = binStr.length()-1; i >=0; i--) {
        dec += (binStr.charAt(i) - '0') * (1 << count++);
    }

    return dec;
}

【讨论】:

  • 非常感谢@zindigo。现在说得通了,我很欣赏详细的解释,它帮助我更好地理解了代码。
猜你喜欢
  • 2015-06-21
  • 2014-10-24
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
相关资源
最近更新 更多