繁体   English   中英

如何在Java中将二进制字符串转换为十进制字符串

[英]How to convert a binary String to a decimal string in Java

我当时正在做作业,以为我完成了,但是老师告诉我这不是他要找的东西,所以我需要知道如何在不使用字符串的情况下将以字符串形式存储的二进制数转换为十进制字符串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();
    }
}

要将基数2(二进制)表示转换为基数10(十进制),请将每个位的值与2 ^(位位置)相乘,然后求和。

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

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

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

要计算2 ^(位位置),我们可以保留位位置的计数,并在每次迭代时增加计数。 然后我们可以做1 <<计数以获得2 ^(位位置)的值。 另外,您也可以执行Math.pow(2,count),但是前者效率更高,因为它只是一个左移指令。

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

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM