Int无法转换为二进制字符串

问题描述 投票:0回答:2
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,但不能将其转换回。

java string int
2个回答
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;

0
投票

Integer::parseInt采用Sting作为参数,但是您已将整数传递给它,因此将不会编译您的代码。另一个问题是您尚未将Integer.toString(product)的值分配给任何内容。如下进行:

public class Main {
    public static void main(String[] args) {
        String a = "10";
        String b = "11";

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

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

输出:

6
© www.soinside.com 2019 - 2024. All rights reserved.