麻烦将十进制值转换为二进制。

huangapple go评论75阅读模式
英文:

Trouble converting decimal value to binary

问题

我正在制作一个程序,用于将十进制值转换为二进制,反之亦然。我已经弄清楚了如何将二进制转换为十进制,但是我在十进制转二进制方面遇到了问题。我已经看过许多关于如何执行此操作的代码来源,但其中大多数涉及使用数组。我不能使用数组,因为这个程序有一个图形用户界面,而 JLabel 无法打印数组。我找到了一段代码,可以用于某些数字,但对其他数字不起作用。以下是代码:

public void convertBinary (int decimal)
{
    String binary = "";
    int remainder;
    
    while (decimal != 0)
    {
        remainder = decimal % 2;
        decimal /= 2;
        binary += remainder;
    }
    lblDecBinAns.setText(String.valueOf(binary));
}

用户输入的给定数字("decimal")在他们按下按钮时输入。我不知道是否可以调整此代码以使其正常工作。也许有一种完全不同的算法可以用于此,或者也许有一种方法可以使用 JLabel 打印数组。我在这个问题上已经被难住了一段时间,所以对任何帮助表示感谢。

附言:
我知道有 .toBinary 函数,但是我必须为这个问题创建自己的方法。

英文:

I'm making a program that converts decimal values to binary and vice versa. I've figured out how to convert binary to decimal, however I am having trouble with decimal to binary. I've seen many sources with code on how to do it but most of them involve using an array. I can't use an array because this program has a GUI and JLabel can't print the array. I've found a code that works with certain numbers, but doesn't with others. Here's the code:

public void convertBinary (int decimal)
    {
        String binary = "";
        int remainder;
        
        while (decimal != 0)
        {
            remainder = decimal % 2;
            decimal /= 2;
            binary += remainder;
        }
        lblDecBinAns.setText(String.valueOf(binary));
                
        
    }

The given number is inputted by the user ("decimal") which is taken when they press the button. I don't know if there's an adjustment that can be made to this code for it to work properly. Perhaps there's an entirely different algorithm that would work for this or maybe a way to print an array with JLabel. I've been stumped on this for a while so any help is appreciated. Thanks.

P.S.
I'm aware of the .toBinary function, but I must create my own method for this one.

答案1

得分: 1

你已经完成了你唯一遗漏的是要反转 `binary` 字符串

    int decimal = 10;
    String binary = "";
    int remainder;

    while (decimal != 0)
    {
        remainder = decimal % 2;
        decimal /= 2;
        binary += remainder;
    }
    System.out.println(new StringBuilder(binary).reverse().toString());

产生的结果是

`1010`
英文:

You got it done, the only thing you are missing is to REVERSE the binary string

int decimal=10;
    String binary = "";
    int remainder;

    while (decimal != 0)
    {
        remainder = decimal % 2;
        decimal /= 2;
        binary += remainder;
    }
    System.out.println(new StringBuilder(binary).reverse().toString());

yelds

1010 as result

答案2

得分: 1

你需要将 remainder 加到 binary = remainder + binary,或者反转字符串。不需要使用 String.valueOf,因为它已经是一个字符串。还要考虑当 decimal 为零时,需要发送 0

public String convertBinary(int decimal) {
    String binary = "";
    int remainder;
    if (decimal == 0) {
        return "0";
    }
    while (decimal != 0) {
        remainder = decimal % 2;
        decimal /= 2;
        binary = remainder + binary;
    }
    return binary;
}
英文:

You need to add remainder as binary = remainder + binary or reverse the string. And no need to use String.valueOf since it's already a string. And also consider the case when decimal is zero you need to send 0

  public String convertBinary(int decimal) {
    String binary = "";
    int remainder;
    if(decimal == 0) {
      return "0";
    }
    while (decimal != 0) {
      remainder = decimal % 2;
      decimal /= 2;
      binary = remainder + binary;
    }
    return binary;
  }

答案3

得分: 0

以下是翻译好的部分:

一个不同的方法是这样的。

  • 将结果初始化为空字符串。
  • 使用 AND & 运算符,屏蔽掉低阶位。你也可以在这里使用余数 % 运算符。
  • 将比特位(1 或 0)转换为字符串,并将其前置到结果字符串。
  • 将数字(decimal)右移 1 位,以便可以检查下一位比特位。<br>
    while(!(decimal&gt;&gt;&gt;1) == 0)
  • 继续循环,直到 decimal == 0(即所有的 1 比特位都已从数字中移出)。
public static String toBinary(int decimal) {
	// 初始化字符串
	String binary = Integer.toString(decimal&amp;1);
    while ((decimal&gt;&gt;&gt;=1) != 0) {
    	binary  =  Integer.toString(decimal&amp;1)+ binary;
        // 或者 binary = Integer.toString(decimal % 2) + binary;
    }
    return binary;
}
英文:

For a different twist, you can also do it like this.

  • Initialize the result to an empty string.
  • Using the AND &amp; operator, mask off the low order bit. You could also use the remainder % operator here too.
  • Convert the bit, 1 or 0, to a string and prepend it to the result string.
  • Right shift the number (decimal) by 1 bit so the next bit can be checked. <br>
    while(!(decimal&gt;&gt;&gt;1) == 0)
  • continue the while loop until decimal == 0 (i.e. all 1 bits have been shifted out of the number).
public static String toBinary(int decimal) {
	// intialize the string
	String binary = Integer.toString(decimal&amp;1);
    while ((decimal&gt;&gt;&gt;=1) != 0) {
    	binary  =  Integer.toString(decimal&amp;1)+ binary;
        // or binary = Integer.toString(decimal % 2) + binary;
    }
    return binary;
}


</details>



# 答案4
**得分**: 0

你尝试过这个吗?
```java
String test = Integer.toString(n, 2); //n是要转换的数字,2表示进制(二进制)。如果你想要一个八进制数,只需将进制改为8。

但是使用这个方法会在你想要将那个String重新转换回数字时引发问题,就像这样:

int number = Integer.parseInt(test); //这会导致NumberFormatException(数字格式异常)。

为了避免这个错误,必须将test的每个字符转换为一个char

char digit = test.charAt(i);

最后,再将每个字符转换回一个单独的String

String converted = String.valueOf(digit);

现在你可以将这个新的String转换为一个int

英文:

Have you tried this?

String test = Integer.toString(n, 2); //n is the number to convert and 2 the base (binary). In case you want an octal number, for example, just change the base to 8.

But using this will cause problem in case you want to reconvert that String into a number just like this:

int number = Integer.parseInt(test); //This will cause NumberFormatException.

To avoid the error, each char of test must be converted to a char

char digit = test.charAt(i);

Finally, convert each char to a individual String again

String converted = String.valueof(digit);

And now you can convert the new String into an int

huangapple
  • 本文由 发表于 2020年9月2日 01:58:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63693055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定