简体   繁体   English

在Java中从二进制转换为十进制

[英]Converting from binary to decimal in Java

I need to write a program that can convert bits into decimal. 我需要编写一个程序,可以将位转换为十进制。 Whenever I enter a bit, it only outputs 0.0. 每当我输入一点时,它只会输出0.0。 I cannot figure out why. 我不知道为什么。 I know it's incredibly simple but I am just not seeing it. 我知道这非常简单,但我只是没有看到。 Any help would be appreciated. 任何帮助,将不胜感激。

import java.lang.Math;
import java.util.Scanner;


public class Lab1 {
    static double number = 0;

    public static double toDec(String num) {

        char[] charArray = num.toCharArray();

        for(int i = 0; i<charArray.length;i++) {
            if(charArray[i] == 1) {
                number = Math.pow(2, charArray.length-i);
            }
        }

        return number;


    }


    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int bit;
        String bitString;

        System.out.println("Please enter a bit");
        bit = keyboard.nextInt();
        bitString = Integer.toString(bit);


        System.out.println(toDec(bitString));



    }

}

You have compared charArray[i] to 1 , but you're comparing apples to oranges, specifically, a char to an int . 您已将charArray[i]1进行了比较,但您将苹果与橙子进行了比较,特别是将charint

Compare to the char '1' instead. 与char'1 '1'比较。

if(charArray[i] == '1') {

Also, you can make number a local variable in toDec ; 另外,您可以在toDec number toDec局部变量; it doesn't need to exist outside that method. 它不需要存在于该方法之外。

In addition, this will only work if one bit is set. 另外,这仅在设置了一位时才有效。 Right now you are working with one bitonly, but if you want to modify this to work with multiple bits, another changes is needed. 现在,您只使用一个位,但是如果要修改它以使用多个位,则需要进行其他更改。

You overwrite number each time toDec is called and the condition is true . 每次调用toDec且条件为true时,您都覆盖number You will probably want to add to number with += instead of overwriting the previous value with = . 您可能想用+=添加到number ,而不是用=覆盖以前的值。

Integer#parseInt(String str, int radix) does the job : Integer#parseInt(String str,int radix)完成工作:

public static Integer toDec(String num) {
  return Integer.parseInt(num, 2);
}

So if you want to take the String "110011" which is 51. For big-endian you are going to have to determine how many bits to process. 因此,如果您要使用字符串“ 110011”(即51)。对于big-endian,您将必须确定要处理的位数。 So if you read the string and it is 6 digits long then you know the first bit has to be shifted 6 places to the left. 因此,如果您读取字符串并且长度为6位,那么您知道第一位必须向左移动6位。

int l = 6;
long value = 0;

for( int i = 0; i < l; i++ )
{
   int bit = ( charArray[i] == "1" ) ? 1 : 0;

   l = l + ( bit << l-i );
}

For float you would basically have to build an interpreter to decode the bits based on however the float is represented in binary. 对于浮点数,您基本上必须构建一个解释器,根据浮点数以二进制表示,以对这些位进行解码。

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

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