【问题标题】:Int cannot be converted to binary string [duplicate]Int 无法转换为二进制字符串 [重复]
【发布时间】:2020-08-03 13:11:36
【问题描述】:
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

    String a = "10";
    String b = "11";

    int a0 = Integer.parseInt(a, 2);
    int b1 = Integer.parseInt(b, 2);

    int product = a0 * b1;
    Integer.toString(product);
    int result = Integer.parseInt(product);
    System.out.print(result);
    }
}

我已经尝试了我在 stackoverflow 中看到的所有方法,但在我的情况下它们都不起作用。我可以将二进制转换为base10,但不能将其转换回来。

【问题讨论】:

  • 错误发生在哪一行?还有……你真的需要解析产品吗?
  • 打印的二进制只是数字的直观表示,例如十进制或十六进制。但是打印整数时的默认设置是以十进制表示形式打印它们。如果你想要一个二进制字符串,只需 String result = Integer.toBinaryString(product);

标签: java string int


【解决方案1】:

在内部,一切都是binary。但在视觉上,二进制只是人类消费的一种表示。其他主要的有octaldecimalhex。但是打印整数时的default 是在decimal representation 中打印它们。如果你想要一个二进制字符串,只需:

    String a = "10";
    String b = "11";

    int a0 = Integer.parseInt(a, 2);
    int b1 = Integer.parseInt(b, 2);

    int product = a0 * b1;
    String result = Integer.toBinaryString(product);
    System.out.print(result);

打印

110

还请注意,您可以为整数分配二进制表示的值。

int a = 0b11;
int b = 0b10;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-31
    • 2013-01-30
    • 2014-06-30
    • 2014-11-28
    • 2023-03-08
    • 2017-05-29
    • 1970-01-01
    • 2014-03-28
    相关资源
    最近更新 更多