Java十进制到二进制 - 二进制的大数

时间:2012-11-06 10:51:07

标签: java binary

我的程序应该将十进制数转换为二进制数。对于大数字,它给我一个负数而不是二进制数。这是为什么?

例如,如果我提供2321,我会收到100100010001,这很好。但如果我供应 241242141我得到-2127232070093227171

我不能使用字符串,数组,函数。还有另一个选项没有将其定义为字符串?输出?

import java.util.Scanner;

public class d {

  public static void main(String[] args) {   

    long num = 0;
    long temp = 0L;

    Scanner sc = new Scanner(System.in);
    num = sc.nextLong();

    long place = 1L;
    long output = 0;
    //System.out.print(""+ num%2+ (num%2)%2);
    while(num != 0) {
      temp = num % 2;
      num = num / 2;    

      output += (place*temp);
      place *=10;
    }

    System.out.print(""+output);    
  }
}

3 个答案:

答案 0 :(得分:3)

你的问题在这里

  output += (place*temp);
  place *=10;

这会产生一个溢出的数字。

一个简单的替代方法是创建一个String,而不是生成一个你将转换为String的数字。

StringBuilder output = new StringBuilder();
while(num != 0) {
  output.append(num & 1);
  num >>>= 1;    
}

System.out.print(output.reverse());   

甚至

StringBuilder output = new StringBuilder();
for(long num = sc.netLong(); num != 0; num >>>= 1) 
  output.append(num & 1);

System.out.print(output.reverse());   

如果您不想使用输入或输出以外的任何功能。

long num = 241242141;
int shift = 63;
while (num >>> shift == 0 && shift > 0) shift--;
for (; shift >= 0; shift--)
    System.out.print((num >>> shift) & 1);

// for comparison only
System.out.println("\n"+Long.toBinaryString(num));

打印

1110011000010001000000011101
1110011000010001000000011101

答案 1 :(得分:1)

问题在于,您将Binary Equivalent存储在long type中,而StringBuilder无法存储如此长的值。

您应该使用remainder - temp并在其中添加 StringBuilder builder = new StringBuilder(); while(num != 0) { temp = num % 2; num = num / 2; builder.append(temp); output += (place*temp); place *=10; } System.out.println(builder.reverse()); 。 然后反向打印: -

methods

如果您不需要使用任何String Concatenation,那么只需使用 String builder = ""; while(num != 0) { temp = num % 2; num = num / 2; builder += temp; output += (place*temp); place *=10; } for (int i = builder.length() - 1; i >= 0; i--) { System.out.print(builder.charAt(i)); } ,然后循环以反向打印字符串: -

String objects

但是,请注意,这会在Heap上创建大量charAt。此外,您在这里使用的是{{1}}方法,您必须使用它。

答案 2 :(得分:1)

使用递归:

public class d {
   static void toBinaryString( long number )
   {
      if( number > 1 ) toBinaryString( number / 2L );
      System.out.print( number % 2L );
   }
   public static void main(String[] args) {
      long num = 241242141L;
      System.out.println( Long.toBinaryString( num ));
      toBinaryString( num );
   }
}

输出:

1110011000010001000000011101
1110011000010001000000011101
相关问题