【问题标题】:Hexadecimal to Binary Error Java十六进制到二进制错误Java
【发布时间】:2015-06-15 08:38:19
【问题描述】:

我正在尝试将十六进制转换为二进制,但问题是结果忽略了我应该在左侧得到的零,这对我来说至关重要。

我的代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scan;
    int num;

    System.out.println("HexaDecimal to Binary");
    scan = new Scanner(System.in);

    System.out.println("\nEnter the number :");
    num = Integer.parseInt(scan.nextLine(), 16);

    String binary = Integer.toBinaryString(num);

    System.out.println("Binary Value is : " + binary);

}

输出: 当我将输入作为0000000000001a000d00 提供时,我应该得到输出为

00000000000000000000000000000000000000000000000000011010000000000000110100000000

但相反,我得到 11010000000000000110100000000 留下初始零。

我应该如何获得确切的数字。 提前致谢。

【问题讨论】:

  • 你得到的数字的准确数字;前导零在位置数字系统中没有影响。
  • @hexafraction 我需要前导零,因为我必须进行异或运算
  • 异或不要求数字在字符串中。您可以只使用 var1^var2,其中两个变量是数字类型。但是,对于非常大的数字,您可能需要使用大整数。
  • @hexafraction 我正在使用异或密码,我需要通过获取二进制值中的每个单个字符来获取异或。我怎样才能得到前导零,因为没有它我的答案会有所不同。
  • 您可能会发现此链接有用:stackoverflow.com/questions/4421400/…

标签: java binary hex


【解决方案1】:

您可以从@JohnH 提供的链接 (How to get 0-padded binary representation of an integer in java?) 中尝试解决方案,并结合计算十六进制数的二进制表示的长度。每个十六进制数字需要4个二进制数字来表示:

public static void main( String[] args ) {
    Scanner scan;
    int num;

    System.out.println("HexaDecimal to Binary");
    scan = new Scanner(System.in);

    System.out.println("\nEnter the number :");
    String input = scan.nextLine().trim();
    num = Integer.parseInt(input, 16);

    int paddedLength = input.length() * 4;
    String binary = String.format("%"+ paddedLength +"s", Integer.toBinaryString(num)).replace(' ', '0');
    System.out.println("Binary Value is : " + binary);
}

它并不完美,但应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2015-12-12
    • 2014-10-30
    • 2014-07-15
    • 2012-11-20
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多